uploaded:2020/08/10
プログラミングの基礎
応用
JavaScript
性質
・大文字と小文字を区別する。
・文末にはセミコロンを使う(単独の文の場合は不要)。
・変数の型は自動で変わる。
・足し算( + )でのみストリング型と数値型の結合を示す。引き算などは文字列が数であれば計算されてしまう。
・バッククォートで囲んだ文字列に${変数}と書くことで、+で繋いでから出力する必要がなくなる。
コメントアウト
//コメント
/*
複数行コメント
*/
データ型
型 | 備考 |
Boolean | ブーリアン型、trueまたはfalse |
null | |
undefined | |
Number | 数値、20や3.1415など |
BigInt | 長整数、9007199254740992nなど |
String | ストリング型、"Hello"など |
Symbol | |
Object | オブジェクト。 |
変数定義
varは基本の変数、letは宣言した場所のスコープブロック内でのみ定義され、constは定数で後から中身を変更できない。
「var a;」といったように、初期値なしで定義した場合、中身の値は「undefined」になる。
var a = 1
let b = 1
const c = 1
配列リテラル
下の場合、二つ目の値はundefinedになる。
let a = [ "apple", "banana", "lemmon" ];
let b = [ "dog", , "cat" ];
console.log(a[0]); //apple
数値リテラル
Number型、BigInt型において、「0o~」で8進数、「0x~」で16進数、「0b~」で2進数。
浮動小数リテラル
整数部分がゼロの場合は省略できる。「e」または「E」で指数表現ができる。
3.1415926
-.123456789
-3.1E+12
.1e-23
オブジェクトリテラル
var food = { type: "fruits", color: "red", taste: "sweet" };
console.log(food.type); //fruits
関数
下の「関数式」では「関数の巻き上げ」に対応しておらず、その文より下でないとその関数が使えない。
function f(x) {
//処理;
//return 戻り値;
};
var g = function() {
//処理;
};
条件分岐
・falseと評価される値
「false」「undefied」「null」「0」「NaN」「""」
if(条件){
//処理;
} else {
//処理;
}
if(条件){
//処理;
} else if(条件){
//処理;
} else {
//処理;
}
switch文
switch(a){
case "apple":
console.log("red");
break;
case "lemmon":
console.log("yellow");
break;
default:
console.log(`I don't know about the color of the ${a}...`);
}
繰り返し処理1
while(条件){
//処理;
}
繰り返し処理2
for(let k = 0; k < 5; k++){
//処理;
}
繰り返し処理3
条件がfalseになるまで繰り返す。
do{
//処理;
}while(条件);
特殊文字のエスケープ
文字 | 意味 |
\0 | ヌル文字 |
\b | バックスペース |
\f | 改ページ |
\n | 改行 |
\r | 復帰 |
\t | タブ |
\v | 垂直タブ |
\' | アポストロフィ |
\" | ダブルクォーテーション |
\\ | バックスラッシュ |
\uXXXX | Unicodeエスケープシーケンス |
・ifなどでくくったbreakやcontinueをそのままぶちこんでループの強制終了や条件に合った回のスキップができる
GLSL
コメントアウト
//コメント
/*
複数行コメント
*/
繰り返し
for(float i = 0.0; i < 5.0; i++){
//処理
}
関数
vec3 myFunction(){
return vec3(0.0);
}
void myFuction2(){
//処理
}
void myFunction3(float a, vec2 b){
//処理
}
void main(){
vec3 v = myFunction();
}
定数
const float a = 3.14;
defineマクロ
基本は定数宣言と同じだが、次のような使い方をすることができる。
#define f float
f a = 1.0;
HTML
コメントアウト
<!-- コメント -->
<!--
複数行コメント
-->
見出し
<h1>見出し</h1>
h1からh6まである
段落
<p>段落</p>
フォントの種類
<font face="MS ゴシック">文字</font>
文字の大きさ
<font size="7">文字</font>
文字の色
<font color="#64ec86">文字</font>
太字・斜体・下線
<b>文字</b>
<i>文字</i>
<u>文字</u>
打消し線
<s>文字</s>
<strike>文字</strike>
ルビ
<ruby><rb>薔薇</rb><rp>(</rp><rt>バラ</rt><rp>)</rp></ruby>
改行
<br>
強調
<em>文字</em>
<strong>文字</strong>
リンク
<a href="#"></a>
・# で同じページ(現在いるページ)
・同じページ内でリンクするなら
「<a href="#link">リンク</a>」セクションへ
<h3 id="link">リンク</h3>
「リンク」セクションへ
・新しいタブを開くなら
<a href="#" target="_blank"></a>
・カーソルを重ねてタイトル表示
<a href="#" title="タイトル"></a>
画像
<img src="image.png" width=240px height=240px alt="代替テキスト">
表
<table border="1">
<tr>
<th>見出し</th>
<td>要素</td>
</tr>
</table>
線
<hr>
↓
↑
ボタン
<button>
<button disabled="disabled">
<button name="名前">
テキストボックス
<textarea></textarea>
<textarea cols="20"></textarea>
<textarea disabled="disabled"></textarea>
<textarea maxlength="100"></textarea>
<textarea name="名前"></textarea>
<textarea readonly="readonly"></textarea>
<textarea required="required"></textarea>
<textarea rows="2"></textarea>
CSSをタグに埋め込む
<○○ style="××: ABC;"></○○>
HTMLのコードにCSSのコードを書く
<style type="text/css"></style>
範囲指定
<div>範囲</div>
<span>範囲</span>
半角スペース適用
<pre>a a</pre>
「<」のエスケープ
&lt;
折り畳み
<details><summary>タイトル</summary>内容</details>
・summaryに折り畳みタブのテキストラベルを書く
CSS
コメントアウト
/*コメント*/
/*
複数行コメント
*/
背景色
background-color: #64ec86;
背景画像
background-image: "img.png";
枠
border: solid 3px #000000;
・一部の場合は「border-top」のようにする。top, bottom, right, leftから選択
・「border-radius」で角を丸く
・通常はsolid, 点線はdotted, 破線はdashed, 二重線はdouble
文字の色
color: #64ec86;
ボックスの並べ方
display: inline;
・inlineまたはblockまたはinline-block
・div要素の横並びはこれを使う
色反転
filter: invert();
フォントの種類
font-family: "sans-serif";
文字の大きさ
font-size: x-large;
・xx-small,x-small,small,medium,large,x-large,xx-largeから選ぶか、数値指定
要素の高さ
height: 20px;
要素の幅
width: 20px;
文字の幅
letter-spacing: 0.5em;
行の幅
line-height: 0.5em;
内側の余白
padding: 10px;
・一部の場合は「padding-top」のようにする。top, bottom, right, leftから選択
padding: 10px 20px;
・このようにすると、上下が10px、左右が20pxになる
padding: 10px 20px;
・このようにすると、上下が10px、左右が20pxになる
外側の余白
margin: 10px;
・一部の場合は「margin-top」のようにする。top, bottom, right, leftから選択
要素の最大の高さ・幅
max-height: 0.5em;
max-width: 0.5em;
要素の最小の高さ・幅
min-height: 0.5em;
min-width: 0.5em;
はみ出した部分
overflow: visible;
・visibleで見えてはみ出す、hiddenで見えずにはみ出す、scrollでスクロール、autoでおさまらないときだけスクロール
・「overflow-x」のようにして上下左右を指定。上下はy
○○揃え
text-align: center;
・left, center, right, justifyから選択
上下ver
vertical-align: top;
・top, middle, bottom, baselineから選択
インデントの大きさ
text-indent: 1em;
テキストの影
text-shadow: 3px 3px 2px #0000ff;
・左右、上下、半径、色
空白の扱い
white-space: normal;
・normalで半角スペースを無視、改行を半角スペースで表示
・preで半角スペースも改行もそのまま表示
・pre-lineで半角スペース無視、改行はそのまま表示
レイヤー
z-index: 100;
・大きいほど上
ズーム
zoom: 150%;
影
box-shadow: 0 3px 4px rgba(0, 0, 0, 0.32);
text-shadow: 0 1px 0 rgba(0,0,0,0.2);
マーカー
background: linear-gradient(transparent 50%, #64ec86 50%);
コピペ禁止
body {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
リンクを青くしない
text-decoration: none;
カーソルを乗せて変化
transition: background-color 1s linear 0 , width 1s linear 0 , height 1s linear 0;
CSSセレクタ
すべての要素
* { a: b; }
特定の要素
div { a: b; }
特定の属性を持った特定の要素
div[width] { a: b; }
div[width=20px] { a: b; }
~で始まる値をもつ属性
a[title^="a"] { a: b; }
~で終わる値をもつ属性
a[title$="z"] { a: b; }
n番目の子要素
div:nth-cild(2n+1) { a: b; }
最初の子要素
div:first-child { a: b; }
最後の子要素
div:last-child { a: b; }
未訪問のリンク
a:link { a: b; }
訪問済みのリンク
a:visited { a: b; }
クリックされた要素
a:active { a: b; }
マウスホバーされた要素
a:hover { a: b; }
要素の最初の行
div::first-line { a: b; }
要素の最初の文字
div::first-letter { a: b; }
要素の直前
div::before { content: "内容"; }
要素の直後
div::after { content: "内容"; }
特定のクラス名の要素
div.class { a: b; }
特定のidの要素
div#id { a: b; }
~に当てはまらない要素
div:not(s) { a: b; }
例)
div:not([title^="a"]) { a: b; }
特定の要素にある特定の子要素
div > span { a: b; }
Python
コメントアウト
# コメント
```
複数行コメント
```
・#とコメント内容の間には半角スペースひとつ入れるのが好ましい
コードの折り込み
a = 1 + 2 + 3 + 4\
+ 5 + 6 + 7 + 8
・あらゆるカッコの中ではjsonのように自由に改行できる
変数定義
a = 1
深層データ
a.b = 1
比較演算子
a == 1
b != 1
c not 1
d < 1
e > 1
f <= 1
g >= 1
論理演算
a == 1 and b == 1
c == 1 or d == 1
・三つ以上でもカッコは要らない
以下のどれでもない
a not in (1, 2, 3, 4, 5)
ストリング型
a = 'Hello world'
・シングルクォーテーションが好ましい
ストリング値の連結
a = 'Hello ' + 'world' # 'Hello world'
b = 'Hello ' 'world' # 'Hello world' (これでも可)
ブーリアン型
a = True
b = False
・大文字に注意。
無の型
a = None
型を取得
type('10') == str # true
・この際の「str」は特殊な型でありストリング型ではない
型の変更
a = int('100') # ストリングの入力を演算に使う際など
b = str(a) # 数とストリングを連結する際など
c = list('Hello') # [ 'H', 'e', 'l', 'l', 'o' ]
リストの要素取得
list_ = ['a', 'b', 'c']
print(list_[1]) # 'b'
リストの要素追加
a = [1, 2, 3, 4]
a.append(5)
print(a) # [1, 2, 3, 4, 5]
文字列の一部を取得
a = 'Hello world'
print(a[3:]) # 'lo world'
print(a[:3]) # 'Hel'
print(a[2:5]) # 'llo '
スペース毎にストリング値を分ける
a = 'Nice to meet you'
print(a.split()) # ['Nice', 'to', 'meet', 'you']
辞書型の要素取得
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(dict['b']) # 'Hi'
辞書の長さ
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(len(dict)) # 3
辞書からキーのみをリスト化
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(list(dict.keys())) # ['a', 'b', 'c']
辞書から値のみをリスト化
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(list(dict.values())) # [1, 'Hi', True]
要素の削除
dict = {'a': 1, 'b': 2, 'c': 3}
dict.pop('b')
print(dict) # {'a': 1, 'c': 3}
現在時刻を取得
import datetime
now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
print(now.hour) # (現在の時間)
ランダムな整数
import random
rand = random.randint(a, b)
重複なしでランダムに取り出す
import random
print(random.sample(list_, 10)
jsonを開く
import json
a = json.load(open('○○.json'))
・辞書型として取得できる
jsonを書き換える
import json
dict = {'a': 'Hi'}
with open('○○.json', 'w') as changed_file:
json.dump(dict, changed_file, indent=2)
条件分岐
if a == b:
# 処理
elif c == d:
# 処理
else:
# 処理
関数定義
def f(x, y):
print(x+y)
print(f(1, 2)) # 3
繰り返し処理
list_ = ['a', 'b', 'c']
for i in list_:
print(i)
# 'a' 'b' 'c' (三回の処理)
int_ = 0
for i in range(3)
int_ += i
# 3
・range(a)は0~aの整数値を順に出力する
例外処理
try:
print(int('Hi'))
except ValueError:
print('Error')
# 'Error'
・IndexErrorでリストの存在しない個数目を指定した場合のエラー
java
性質
・整数/整数は整数、つまり「10/3」は「3」となってしまうため、「10.0f/3.0f」としなくてはならない。
HelloWorld
一行目「class」の右の単語はファイル名「○○.java」の「○○」と一致させなくてはならない。
public class Main{
public static void main(String[] args){
System.out.println("Hello World!");
}
}
ファイルの実行
一度.classファイルにコンパイルしてから、Main(クラス)を実行する
$ javac Main.java
$ java Main
データ型
型 | 備考 |
byte | 8ビット符号つき整数。-128 から 127 まで |
short | 16ビット符号つき整数。-32768 から 32767 まで |
int | 32ビット符号つき整数。-2147483648 から 2147483647 まで |
long | 64ビット符号つき整数。-9223372036854775808 から 9223372036854775807 まで |
double | 小数型、3.14など |
float | 浮動小数型、3.14Fなど |
char | 文字型、'A'など シングルクォーテーションを使う |
boolean | trueまたはfalse |
String | ストリング型、"Hello"など ダブルクォーテーションを使う 「S」は大文字 |
整数型リテラル
普通の整数型はint型として扱われ、末尾に「L」をつけるとlong型になる。
「0b~」で2進数、「0~」で8進数、「0x~」で16進数を表す。
また、表記内の「 _ 」は無視される
小数型リテラル
普通の小数はdouble型として扱われ、末尾に「F」をつけるとfloat型になる。
また、表記内の「 _ 」は無視される。
配列
int[] a = new int[5];
a[0] = 1;
int[] a = { 1, 2, 3 };
条件分岐
if (条件) {
//処理;
} else {
//処理;
}
if (条件) {
//処理;
} else if(条件) {
//処理;
} else {
//処理;
}
関数(メソッド)
private static double calcS(double a,double b){
double S = a * b;
return S;
}
プログラム全体ではこのようになる。
public class Main{
public static void main(String[] args){
System.out.println(factr(6));
}
private static int factr(int x){
int k = 1;
int y = 1;
do{
y *= k;
k++;
} while(k<=x);
return y;
}
}
switch文
switch(変数) {
case 値1:
case 値2:
// 値1 か値 2 のときここが実行される
break;
case 値3:
// 値3 のときにここが実行される
break;
default:
// 値1, 2, 3 のいずれでもない時にここが実行される
break;
}
繰り返し処理
while(条件){
//処理;
}
while (i < 3) {
System.out.println(i);
i++;
} // 0 1 2
繰り返し処理2
何か処理を実行して処理の結果を評価し、成功するまで繰り返す、といったようなものを作るときに使う。
do{
//処理;
} while(条件);
繰り返し処理3
for (int i = 0; i < 3; i++) {
//処理;
}
int[] a = {1, 2, 3};
for (int i : a) {
//処理;
}
特殊文字のエスケープ
文字 | 意味 |
\t | 水平タブ文字 |
\b | バックスペース |
\n | 改行 |
\r | キャリッジリターン |
\f | 書式送り(Form Feed) |
\' | アポストロフィ |
\" | ダブルクォーテーション |
\\ | バックスラッシュ |
\uXXXX | Unicodeエスケープシーケンス |
文字列から数値を読み取る
int i = Integer.parseInt("123");
ターミナルから整数の入力を受けとる
import java.util.Scanner;
import java.util.InputMismatchException;
public class Main{
public static void main(String[] args){
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Input > ");
int t = scanner.nextInt();
System.out.println(t * t);
scanner.close();
} catch (InputMismatchException e) {
System.out.println("Please input the integer.");
}
}
HTMLでJavaScriptを使う
参考
指定idの要素を取得
var val = document.getElementById("id");
指定classの要素を取得
var val1 = document.getElementsByClassName("class");
var val2 = element.getElementsByClassName("class");
HTMLCollectionというアレイで返ってくる
指定idのcssの値を取得
var element1 = document.getElementById("id");
var element2 = getComputedStyle(element).padding
cssの値を変える
documents.getElementById("id").style.fontSize = "20px";
画面の大きさ
var val = window.innerWidth;
画面の形によってスタイルを変更
横長なら赤く、縦長なら青くなる例(リアルタイム)
<script type="text/javascript">
//読み込み時の表示
window_load();
//ウィンドウサイズ変更時に更新
window.onresize = window_load;
//サイズの表示
function window_load() {
if(window.innerWidth > window.innerHeight){ //横長
document.getElementById("test").style.color = "#f00";
} else { //縦長
document.getElementById("test").style.color = "#00f";
}
}
</script>
constructed by: Masec Rinca