branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
listlengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>timkwali/Payment_App<file_sep>/app/build.gradle
plugins {
id 'com.android.application'
id 'dagger.hilt.android.plugin'
}
android {
compileSdkVersion 31
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.payoneer.paymentapp"
minSdkVersion 21
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "com.payoneer.paymentapp.utils.MockTestRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.0'
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation 'androidx.test:rules:1.4.0'
androidTestImplementation 'androidx.test:runner:1.4.0'
androidTestImplementation('com.android.support.test.espresso:espresso-contrib:3.0.2') {
// Necessary to avoid version conflicts
exclude group: 'com.android.support', module: 'appcompat'
exclude group: 'com.android.support', module: 'support-v4'
exclude group: 'com.android.support', module: 'support-annotations'
exclude module: 'recyclerview-v7'
}
//Mockito
testImplementation 'org.mockito:mockito-core:4.0.0'
androidTestImplementation 'org.mockito:mockito-android:4.0.0'
testImplementation 'android.arch.core:core-testing:1.1.1'
//Mockwebserver
testImplementation("com.squareup.okhttp3:mockwebserver:4.7.2")
androidTestImplementation "com.squareup.okhttp3:mockwebserver:4.7.2"
//Okhttp Idling Resource
androidTestImplementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'
//Material design
implementation 'com.google.android.material:material:1.5.0-alpha05'
implementation fileTree(dir: 'libs', include: ['*.jar'])
def nav_version = "2.4.0-alpha10"
implementation "androidx.cardview:cardview:1.0.0"
implementation 'com.google.android.material:material:1.4.0'
implementation 'com.android.support:multidex:1.0.3'
// Hilt
implementation 'com.google.dagger:hilt-android:2.35'
annotationProcessor 'com.google.dagger:hilt-android-compiler:2.35'
androidTestAnnotationProcessor 'com.google.dagger:hilt-android-compiler:2.35'
androidTestImplementation "com.google.dagger:hilt-android-testing:2.35"
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.2"
implementation "com.squareup.okhttp3:logging-interceptor:4.9.0"
implementation "com.github.akarnokd:rxjava3-retrofit-adapter:3.0.0"
// ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.3.1'
// LiveData
implementation 'androidx.lifecycle:lifecycle-livedata:2.3.1'
// Navigation
implementation "androidx.navigation:navigation-fragment:$nav_version"
implementation "androidx.navigation:navigation-ui:$nav_version"
// Glide
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
//Shimmer
implementation 'com.facebook.shimmer:shimmer:0.5.0'
}<file_sep>/app/src/androidTest/java/com/payoneer/paymentapp/utils/OkHttpProvider.java
package com.payoneer.paymentapp.utils;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
public class OkHttpProvider {
// Timeout for the network requests
private static Long REQUEST_TIMEOUT = 3L;
private static OkHttpClient okHttpClient = null;
public static OkHttpClient getOkHttpClient() {
if(okHttpClient == null) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.connectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.build();
OkHttpProvider.okHttpClient = okHttpClient;
return okHttpClient;
} else {
return okHttpClient;
}
}
}
<file_sep>/app/src/main/java/com/payoneer/paymentapp/repository/Repository.java
package com.payoneer.paymentapp.repository;
import com.payoneer.paymentapp.model.PaymentsResponse;
import retrofit2.Call;
public interface Repository {
Call<PaymentsResponse> getPayments();
}
<file_sep>/app/src/androidTest/java/com/payoneer/paymentapp/PaymentsUiTest.java
package com.payoneer.paymentapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.Espresso;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.action.ViewActions;
import androidx.test.espresso.assertion.ViewAssertions;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.espresso.matcher.ViewMatchers;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.jakewharton.espresso.OkHttp3IdlingResource;
import com.payoneer.paymentapp.ui.MainActivity;
import com.payoneer.paymentapp.utils.Constants;
import com.payoneer.paymentapp.utils.FileReader;
import com.payoneer.paymentapp.utils.OkHttpProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.util.Objects;
import dagger.hilt.android.testing.HiltAndroidRule;
import dagger.hilt.android.testing.HiltAndroidTest;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
public class PaymentsUiTest {
@Rule
public HiltAndroidRule hiltAndroidRule = new HiltAndroidRule(this);
private MockWebServer mockWebServer = new MockWebServer();
@Before
public void setup() throws IOException {
mockWebServer.start(8080);
IdlingRegistry.getInstance().register(OkHttp3IdlingResource.create(
"okhttp",
OkHttpProvider.getOkHttpClient()
));
}
@After
public void teardown() throws IOException {
mockWebServer.shutdown();
}
private void setUpMockWebServer(int code, @Nullable String body) {
mockWebServer.setDispatcher(new Dispatcher() {
@NonNull
@Override
public MockResponse dispatch(@NonNull RecordedRequest recordedRequest) {
MockResponse mockResponse = null;
try {
mockResponse = new MockResponse()
.setResponseCode(code)
.setBody(Objects.requireNonNull(FileReader.readStringFromFile(body)));
} catch (IOException exception) {
exception.printStackTrace();
}
return mockResponse;
}
});
}
@Test
public void successfulResponse_shows_correctSnackBar_fromRecyclerView() {
setUpMockWebServer(Constants.successCode, "success_response.json");
ActivityScenario.launch(MainActivity.class);
Espresso.onView(ViewMatchers.withId(R.id.home_fragment))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(R.id.payments_rv))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))
.perform(RecyclerViewActions.actionOnItemAtPosition(0, ViewActions.click()));
Espresso.onView(ViewMatchers.withId(com.google.android.material.R.id.snackbar_text))
.check(ViewAssertions.matches(ViewMatchers.withText("American Express")));
}
@Test
public void emptyResponse_returns_emptyResultSnackBar() {
setUpMockWebServer(Constants.emptyResourceCode, null);
ActivityScenario.launch(MainActivity.class);
Espresso.onView(ViewMatchers.withId(R.id.home_fragment))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(com.google.android.material.R.id.snackbar_text))
.check(ViewAssertions.matches(ViewMatchers.withText(Constants.errorHeading + "\n"+ Constants.emptyResultMessage)));
}
@Test
public void noResourceResponse_returns_noResourceSnackBar() {
setUpMockWebServer(Constants.noResourceCode, null);
ActivityScenario.launch(MainActivity.class);
Espresso.onView(ViewMatchers.withId(R.id.home_fragment))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(com.google.android.material.R.id.snackbar_text))
.check(ViewAssertions.matches(ViewMatchers.withText(Constants.errorHeading + "\n"+ Constants.noResourceMessage)));
}
@Test
public void responseTimeout_returns_timeoutSnackBar() {
setUpMockWebServer(Constants.timeoutCode, null);
ActivityScenario.launch(MainActivity.class);
Espresso.onView(ViewMatchers.withId(R.id.home_fragment))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(com.google.android.material.R.id.snackbar_text))
.check(ViewAssertions.matches(ViewMatchers.withText(Constants.errorHeading + "\n"+ Constants.timeoutMessage)));
}
@Test
public void serverError_returns_serverErrorSnackBar() {
setUpMockWebServer(Constants.serverErrorCode, null);
ActivityScenario.launch(MainActivity.class);
Espresso.onView(ViewMatchers.withId(R.id.home_fragment))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(com.google.android.material.R.id.snackbar_text))
.check(ViewAssertions.matches(ViewMatchers.withText(Constants.errorHeading + "\n"+ Constants.serverErrorMessage)));
}
@Test
public void otherError_returns_errorMessageSnackBar() {
setUpMockWebServer(504, null);
ActivityScenario.launch(MainActivity.class);
Espresso.onView(ViewMatchers.withId(R.id.home_fragment))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(com.google.android.material.R.id.snackbar_text))
.check(ViewAssertions.matches(ViewMatchers.withText(Constants.errorHeading + "\n"+ Constants.errorMessage)));
}
@Test
public void swipeToRefresh_refreshesTheApp() {
setUpMockWebServer(Constants.successCode, "success_response.json");
ActivityScenario.launch(MainActivity.class);
Espresso.onView(ViewMatchers.withId(R.id.home_fragment))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(R.id.payments_rv))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
Espresso.onView(ViewMatchers.withId(R.id.swipe_refresh))
.perform(ViewActions.swipeDown());
Espresso.onView(ViewMatchers.withId(R.id.payments_rv))
.perform(RecyclerViewActions.actionOnItemAtPosition(0, ViewActions.click()));
Espresso.onView(ViewMatchers.withId(com.google.android.material.R.id.snackbar_text))
.check(ViewAssertions.matches(ViewMatchers.withText("American Express")));
}
}
<file_sep>/app/src/main/java/com/payoneer/paymentapp/repository/RepositoryImpl.java
package com.payoneer.paymentapp.repository;
import com.payoneer.paymentapp.model.PaymentsResponse;
import com.payoneer.paymentapp.network.ApiService;
import com.payoneer.paymentapp.network.Resource;
import javax.inject.Inject;
import retrofit2.Call;
public class RepositoryImpl implements Repository {
private final ApiService apiService;
private Resource<PaymentsResponse> resource;
@Inject
public RepositoryImpl (ApiService apiService) {
this.apiService = apiService;
}
@Override
public Call<PaymentsResponse> getPayments() {
return apiService.getPayments();
}
}
<file_sep>/app/src/main/java/com/payoneer/paymentapp/viewmodel/PaymentsViewModel.java
package com.payoneer.paymentapp.viewmodel;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.payoneer.paymentapp.model.PaymentsResponse;
import com.payoneer.paymentapp.network.Resource;
import com.payoneer.paymentapp.repository.Repository;
import com.payoneer.paymentapp.utils.Utils;
import javax.inject.Inject;
import dagger.hilt.android.lifecycle.HiltViewModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@HiltViewModel
public class PaymentsViewModel extends ViewModel {
private final Repository repository;
@Inject
public PaymentsViewModel(Repository repository) { this.repository = repository; }
private final MutableLiveData<Resource<PaymentsResponse>> _paymentsList = new MutableLiveData<Resource<PaymentsResponse>>();
public LiveData<Resource<PaymentsResponse>> paymentsList() {
return _paymentsList;
}
public void getPayments() {
_paymentsList.setValue(Resource.loading(null));
repository.getPayments().enqueue(new Callback<PaymentsResponse>() {
@Override
public void onResponse(Call<PaymentsResponse> call, Response<PaymentsResponse> response) {
PaymentsResponse responseBody = response.body();
int responseCode = response.code();
Resource resource = Utils.getResource(responseCode, responseBody);
_paymentsList.setValue(resource);
}
@Override
public void onFailure(Call<PaymentsResponse> call, Throwable throwable) {
Resource resource;
String message = throwable.getMessage();
if(message != null) {
Log.e("errorTag", "getPayments: " + message);
resource = Resource.error(message, throwable);
} else {
resource = Resource.error("Check your network connection.", null);
}
_paymentsList.setValue(resource);
}
});
}
}
<file_sep>/README.md
# Payment_App
* An app showing different payment platforms.
* A beautiful splash screen greets you when you open the app.
* App has swipe to refresh feature.
* You can also refresh the list of items from the options menu.
* Unit and instumentation tests have been written to test the app.
* More features coming soon.
## Screenshots
<img width="220" alt="payment_app_1" src="https://user-images.githubusercontent.com/46701145/139244854-faa4b037-e5de-422b-9074-7f58ebc3b671.png"> <img width="220" alt="payment_app_2" src="https://user-images.githubusercontent.com/46701145/139244863-427e655a-91e5-41f5-926e-29b0bd583fa1.png"> <img width="220" alt="payment_app_3" src="https://user-images.githubusercontent.com/46701145/139244871-05f01a2d-b6e2-414d-ad04-51ec487b1925.png">
<img width="220" alt="payment_app_4" src="https://user-images.githubusercontent.com/46701145/139244874-458e1dfa-72ef-4e7d-93cd-db08cd8a2e70.png"> <img width="220" alt="payment_app_5" src="https://user-images.githubusercontent.com/46701145/139244878-62604677-96de-4bf1-b777-1f02dc3f9131.png"> <img width="220" alt="payment_app_6" src="https://user-images.githubusercontent.com/46701145/139244881-9909bbfc-eb80-4755-ad49-fa887b3de121.png">
<file_sep>/app/src/test/java/com/payoneer/paymentapp/utils/TestUtils.java
package com.payoneer.paymentapp.utils;
import androidx.annotation.Nullable;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
public class TestUtils {
public static ResponseBody emptyResponseBody = ResponseBody.create(MediaType.parse("application/json"), "");
public static <T> Call<T> fakeSuccessCall(@Nullable T body, int code) {
return new Calls.FakeCall<>(Response.success(code, body), null);
}
public static <T> Call<T> fakeErrorCall(@Nullable T body, int code) {
if(body == null) {
body = (T) emptyResponseBody;
}
return new Calls.FakeCall<T>(Response.error(code, (ResponseBody) body), null);
}
public static String PAYMENT_RESPONSE = "{\n" +
" \"links\": {\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/checkout.json\"\n" +
" },\n" +
" \"timestamp\": \"2021-04-14T09:16:46.796+0000\",\n" +
" \"operation\": \"LIST\",\n" +
" \"resultCode\": \"00000.11.000\",\n" +
" \"resultInfo\": \"17 applicable and 0 registered networks are found\",\n" +
" \"returnCode\": {\n" +
" \"name\": \"OK\",\n" +
" \"source\": \"GATEWAY\"\n" +
" },\n" +
" \"status\": {\n" +
" \"code\": \"listed\",\n" +
" \"reason\": \"listed\"\n" +
" },\n" +
" \"interaction\": {\n" +
" \"code\": \"PROCEED\",\n" +
" \"reason\": \"OK\"\n" +
" },\n" +
" \"identification\": {\n" +
" \"longId\": \"6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it\",\n" +
" \"shortId\": \"05753-51161\",\n" +
" \"transactionId\": \"20678\"\n" +
" },\n" +
" \"networks\": {\n" +
" \"applicable\": [\n" +
" {\n" +
" \"code\": \"AMEX\",\n" +
" \"label\": \"American Express\",\n" +
" \"method\": \"CREDIT_CARD\",\n" +
" \"grouping\": \"CREDIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/amex.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/AMEX\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/AMEX.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/AMEX/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/AMEX/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"DINERS\",\n" +
" \"label\": \"Diners Club\",\n" +
" \"method\": \"CREDIT_CARD\",\n" +
" \"grouping\": \"CREDIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/diners.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/DINERS\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/DINERS.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/DINERS/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/DINERS/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"DISCOVER\",\n" +
" \"label\": \"Discover\",\n" +
" \"method\": \"CREDIT_CARD\",\n" +
" \"grouping\": \"CREDIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/discover.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/DISCOVER\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/DISCOVER.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/DISCOVER/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/DISCOVER/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"IDEAL\",\n" +
" \"label\": \"iDEAL\",\n" +
" \"method\": \"ONLINE_BANK_TRANSFER\",\n" +
" \"grouping\": \"ONLINE_BANK_TRANSFER\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": true,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/ideal.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/IDEAL\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/IDEAL.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/IDEAL/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/IDEAL/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"bic\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"MAESTRO\",\n" +
" \"label\": \"Maestro\",\n" +
" \"method\": \"DEBIT_CARD\",\n" +
" \"grouping\": \"DEBIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/maestro.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MAESTRO\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/MAESTRO.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MAESTRO/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/MAESTRO/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"MASTERCARD\",\n" +
" \"label\": \"Mastercard\",\n" +
" \"method\": \"CREDIT_CARD\",\n" +
" \"grouping\": \"CREDIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/mastercard.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MASTERCARD\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/MASTERCARD.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MASTERCARD/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/MASTERCARD/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"MISTERCASH\",\n" +
" \"label\": \"Bancontact/Mister Cash\",\n" +
" \"method\": \"DEBIT_CARD\",\n" +
" \"grouping\": \"DEBIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/mistercash.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MISTERCASH\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/MISTERCASH.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MISTERCASH/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/MISTERCASH/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"PAYFAST\",\n" +
" \"label\": \"PayFast\",\n" +
" \"method\": \"WALLET\",\n" +
" \"grouping\": \"WALLET\",\n" +
" \"registration\": \"NONE\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": true,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/payfast.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/PAYFAST\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/PAYFAST.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/PAYFAST/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/PAYFAST/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"PAYPAL\",\n" +
" \"label\": \"PayPal\",\n" +
" \"method\": \"WALLET\",\n" +
" \"grouping\": \"WALLET\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": true,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/paypal.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/PAYPAL\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/PAYPAL.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/PAYPAL/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/PAYPAL/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"contractData\": {\n" +
" \"PAGE_ENVIRONMENT\": \"sandbox\",\n" +
" \"JAVASCRIPT_INTEGRATION\": \"false\",\n" +
" \"PAGE_BUTTON_LOCALE\": \"en_US\"\n" +
" },\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"POSTEPAY\",\n" +
" \"label\": \"PostePay\",\n" +
" \"method\": \"DEBIT_CARD\",\n" +
" \"grouping\": \"DEBIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/postepay.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/POSTEPAY\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/POSTEPAY.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/POSTEPAY/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/POSTEPAY/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"RATEPAY\",\n" +
" \"label\": \"RatePAY Invoice\",\n" +
" \"method\": \"OPEN_INVOICE\",\n" +
" \"grouping\": \"OPEN_INVOICE\",\n" +
" \"registration\": \"NONE\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/ratepay.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/RATEPAY\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/RATEPAY.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/RATEPAY/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/RATEPAY/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"SEPADD\",\n" +
" \"label\": \"SEPA\",\n" +
" \"method\": \"DIRECT_DEBIT\",\n" +
" \"grouping\": \"DIRECT_DEBIT\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/sepadd.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/SEPADD\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/SEPADD.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/SEPADD/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/SEPADD/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"iban\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"bic\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"SOFORTUEBERWEISUNG\",\n" +
" \"label\": \"Online Bank Transfer\",\n" +
" \"method\": \"ONLINE_BANK_TRANSFER\",\n" +
" \"grouping\": \"ONLINE_BANK_TRANSFER\",\n" +
" \"registration\": \"NONE\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": true,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/sofort.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/SOFORTUEBERWEISUNG\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/SOFORTUEBERWEISUNG.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/SOFORTUEBERWEISUNG/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/SOFORTUEBERWEISUNG/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"UNIONPAY\",\n" +
" \"label\": \"UnionPay\",\n" +
" \"method\": \"CREDIT_CARD\",\n" +
" \"grouping\": \"CREDIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/unionpay.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/UNIONPAY\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/UNIONPAY.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/UNIONPAY/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/UNIONPAY/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"VISA\",\n" +
" \"label\": \"Visa\",\n" +
" \"method\": \"CREDIT_CARD\",\n" +
" \"grouping\": \"CREDIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/visa.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/VISA\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/VISA.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/VISA/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/VISA/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"VISAELECTRON\",\n" +
" \"label\": \"Visa Electron\",\n" +
" \"method\": \"DEBIT_CARD\",\n" +
" \"grouping\": \"DEBIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/visaelectron.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/VISAELECTRON\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/VISAELECTRON.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/VISAELECTRON/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/VISAELECTRON/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" },\n" +
" {\n" +
" \"code\": \"VISA_DANKORT\",\n" +
" \"label\": \"Visa Dankort\",\n" +
" \"method\": \"DEBIT_CARD\",\n" +
" \"grouping\": \"DEBIT_CARD\",\n" +
" \"registration\": \"OPTIONAL\",\n" +
" \"recurrence\": \"NONE\",\n" +
" \"redirect\": false,\n" +
" \"links\": {\n" +
" \"logo\": \"https://raw.githubusercontent.com/optile/checkout-android/develop/checkout/src/main/assets/networklogos/visa_dankort.png\",\n" +
" \"self\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/VISA_DANKORT\",\n" +
" \"lang\": \"https://resources.integration.oscato.com/resource/lang/MOBILETEAM/en_US/VISA_DANKORT.json\",\n" +
" \"operation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/VISA_DANKORT/charge\",\n" +
" \"validation\": \"https://api.integration.oscato.com/pci/v1/6076b2feabe8170009d56de4l7ab1tlvai852jekk4s2h2b7it/MOBILETEAM/en_US/VISA_DANKORT/standard/validate\"\n" +
" },\n" +
" \"selected\": false,\n" +
" \"inputElements\": [\n" +
" {\n" +
" \"name\": \"number\",\n" +
" \"type\": \"numeric\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryMonth\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"expiryYear\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"verificationCode\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" {\n" +
" \"name\": \"holderName\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ],\n" +
" \"operationType\": \"CHARGE\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"operationType\": \"CHARGE\",\n" +
" \"style\": {\n" +
" \"language\": \"en_US\"\n" +
" },\n" +
" \"payment\": {\n" +
" \"reference\": \"Mobile Team Exercise\",\n" +
" \"amount\": 13,\n" +
" \"currency\": \"EUR\"\n" +
" },\n" +
" \"integrationType\": \"MOBILE_NATIVE\"\n" +
"}";
}
<file_sep>/app/src/main/java/com/payoneer/paymentapp/di/RetrofitModule.java
package com.payoneer.paymentapp.di;
import com.payoneer.paymentapp.utils.Constants;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.components.SingletonComponent;
import hu.akarnokd.rxjava3.retrofit.RxJava3CallAdapterFactory;
import retrofit2.Converter;
import retrofit2.Retrofit;
@Module
@InstallIn(SingletonComponent.class)
public class RetrofitModule {
@Provides
@Singleton
public static Retrofit provideRetrofitService(Converter.Factory converterFactory) {
return new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build();
}
}
<file_sep>/app/src/main/java/com/payoneer/paymentapp/model/Networks.java
package com.payoneer.paymentapp.model;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class Networks{
@SerializedName("applicable")
private List<ApplicableItem> applicable;
public void setApplicable(List<ApplicableItem> applicable){
this.applicable = applicable;
}
public List<ApplicableItem> getApplicable(){
return applicable;
}
}
|
91d67cf41907c835658a6376827b4a7a91103f78
|
[
"Java",
"Markdown",
"Gradle"
] | 10 |
Java
|
timkwali/Payment_App
|
d6bd6f0345b19f2ff6778ebc43eb7a22e84fd7b6
|
69117f1efb7e4d5e5f724871fade4c550d6c0a4b
|
refs/heads/master
|
<repo_name>rutvijjethwa/hashutil<file_sep>/hashutil.py
import hashlib
import sys
from optparse import OptionParser
#############################################################
# File Hasher
def fileHasher(fileToHash):
"""Return a string of Hash
Takes file object as input.
Make sure to open the file in read-binary mode. for ex. open('abc.txt','rb')"""
sha = hashlib.sha256()
try:
with open(file=fileToHash, mode="rb") as fileObject:
sha.update(fileObject.read())
return sha.hexdigest()
except FileNotFoundError:
print("INPUT ERROR : File Does Not Exist")
##############################################################
# Option Parser
def decorator(arg1):
"""Decorator to warp Hashing module
Return Hashed string
"""
def choice(func):
print("Argument for Hashing {}".format(arg1))
x = func()
if type(arg1) is str:
x.update(arg1.encode('ascii'))
else:
try:
x.update(arg1.read())
except AttributeError:
print("INVALID INPUT")
sys.exit(0)
spam = x.hexdigest()
assert isinstance(spam, str)
return spam
return choice
###########################
def hashMD5():
"""Returns and MD5 Hashlib Object"""
hashObject = hashlib.md5()
return hashObject
def hashSHA1():
"""Returns and SHA1 Hashlib Object"""
hashObject = hashlib.sha1()
return hashObject
def hashSHA224():
"""Returns and SHA224 Hashlib Object"""
hashObject = hashlib.sha224()
return hashObject
def hashSHA256():
"""Returns and SHA256 Hashlib Object"""
hashObject = hashlib.sha256()
return hashObject
def hashSHA384():
"""Returns and 384 Hashlib Object"""
hashObject = hashlib.sha384()
return hashObject
def hashSHA512():
"""Returns and SHA512 Hashlib Object"""
hashObject = hashlib.sha512()
return hashObject
# decorator(stringHash)(hashMD5) #solution
#################################################################
if __name__ == '__main__':
# List of Supported Hash
supportedHash = ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']
#############################################################
# Input Processing
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename", action="store",
help="File input for hashing", metavar="FILE")
parser.add_option("-s", "--string", dest="stringHash", action="store",
help="String input for hashing", metavar="String")
parser.add_option("-c", "--compare", dest="inputHash", action="store", metavar="Hash_String",
help="Input the string to match with the file. Use along with -f option.")
parser.add_option("-a", "--hash", dest="hashAlgo", action="store", metavar="Hashing_Algorithm",
help="Hashing algorithm to use. Default is sha256"
"\nAvailable Options :'md5', 'sha1','sha224', 'sha256', 'sha384', 'sha512'")
(options, args) = parser.parse_args()
####################################################################################################
if options.filename is not None:
print("Hash for the file '{0}' is {1}".format(options.filename, fileHasher(options.filename)))
# print("Hash for the file '{0}' is {1}".format(options.filename, decorator(options.filename)(hashSHA256)))
if options.inputHash is not None:
print('Compare string MATCHED') if (options.inputHash == fileHasher(options.filename)) else print(
"Compare string does NOT MATCH")
##################################################################################################
if options.filename is None:
if options.hashAlgo is not None and options.hashAlgo.lower() in supportedHash:
decInput = options.stringHash
# decorator(stringHash)(hashMD5) #solution
if options.hashAlgo.lower() == 'md5':
stringHashOutput = decorator(options.stringHash)(hashMD5)
print("Hash Output: " + stringHashOutput)
elif options.hashAlgo.lower() == 'sha1':
stringHashOutput = decorator(options.stringHash)(hashSHA1)
print("Hash Output: " + stringHashOutput)
elif options.hashAlgo.lower() == 'sha224':
stringHashOutput = decorator(options.stringHash)(hashSHA224)
print("Hash Output: " + stringHashOutput)
elif options.hashAlgo.lower() == 'sha384':
stringHashOutput = decorator(options.stringHash)(hashSHA384)
print("Hash Output: " + stringHashOutput)
elif options.hashAlgo.lower() == 'sha512':
stringHashOutput = decorator(options.stringHash)(hashSHA512)
print("Hash Output: " + stringHashOutput)
else:
stringHashOutput = decorator(options.stringHash)(hashSHA256)
print("Hash Output: " + stringHashOutput)
###################################################################################################
# COMPARE
###################################################################################################
if options.inputHash is not None and options.filename is None:
print('Compare string MATCHED') if (options.inputHash == stringHashOutput) else print(
'Compare string does NOT MATCH')
<file_sep>/README.md
# Hashutil
Basic hashing utility
```text
Usage: hashutil.py [options]
Options:
-h, --help show this help message and exit
-f FILE, --file=FILE File input for hashing
-s String, --string=String
String input for hashing
-c Hash_String, --compare=Hash_String
Input the string to match with the file. Use along
with -f option.
-a Hashing_Algorithm, --hash=Hashing_Algorithm
Hashing algorithm to use. Default is sha256 Avaliable
Options :'md5', 'sha1','sha224', 'sha256', 'sha384',
'sha512'
```
### Sample Command
```commandline
python hashutil.py --file=abc.txt
```
```commandline
python hashutil.py -f abc.txt
```
|
89ccac5e246ad1bf2bbb4f3c10495ee1b6771ba0
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
rutvijjethwa/hashutil
|
e88b86554fdb0cc3342c98cab5e1ccf7db1c5f43
|
1a4c4b4095c51258b9371a4369c7afca05b1216f
|
refs/heads/master
|
<repo_name>wakuwakupark/gamematome<file_sep>/GameMatome/MemoViewController.h
//
// FavoriteViewController.h
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
//@class Item;
@class Site;
@class News;
@class Memo;
@class GADBannerView;
@interface MemoViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
NSArray* gamesArray; //ゲームエンティティが格納される配列
NSMutableArray* newsArray; //表示用ニュース配列
//引っ張って更新
UIRefreshControl *_refreshControl;
Memo* editingMemo;
NSString* initialTextOfEditingMemo;
GADBannerView* bannerView;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *backgroundView;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIButton *editDoneButton;
- (IBAction)editDoneButtonPressed:(id)sender;
@end
/*
起動
設定でチェック済のゲームにかんするRSSからデータを引っ張る
セルにタッチでブラウザviewに以降
お気に入り登録
未読は文字を太く
*/<file_sep>/GameMatome/Game.m
//
// Game.m
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "Game.h"
#import "Site.h"
@implementation Game
@dynamic name;
@dynamic unuse;
@dynamic sites;
@dynamic gameId;
- (void)changeUnuseState:(int)value
{
[self setUnuse:@(value)];
for (Site* s in [self sites]) {
[s changeUnuseState:value];
}
}
@end
<file_sep>/GameMatome/MemoViewController.m
//
// FavoriteViewController.m
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "MemoViewController.h"
#import "BrouserViewController.h"
#import "ForUseCoreData.h"
#import "Game.h"
#import "Site.h"
#import "News.h"
#import "Memo.h"
#import "GADBannerView.h"
@interface MemoViewController ()
@end
@implementation MemoViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//広告の設定
bannerView = [[GADBannerView alloc]initWithAdSize:kGADAdSizeBanner];
bannerView.adUnitID = @"ca-app-pub-9624460734614700/2538576676";
bannerView.rootViewController = self;
[self.view addSubview:bannerView];
[bannerView loadRequest:[GADRequest request]];
[bannerView setFrame:CGRectMake(0, 470, 320, 50)];
_tableView.dataSource = self;
_tableView.delegate = self;
_backgroundView.hidden = YES;
_textView.hidden = YES;
_editDoneButton.hidden = YES;
// _refreshControl = [[UIRefreshControl alloc] init];
// [_refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
// [_tableView addSubview:_refreshControl];
[self registerForKeyboardNotifications];
}
- (void)viewWillDisappear:(BOOL)animated
{
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
- (void)viewDidAppear:(BOOL)animated
{
[self setNewsHavingMemo];
[_tableView reloadData];
}
- (void)refresh
{
[_refreshControl endRefreshing];
[self setNewsHavingMemo];
[_tableView reloadData];
}
- (void)endRefresh
{
[_refreshControl endRefreshing];
}
#pragma mark UITableView Delegate
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
News* selected = [newsArray objectAtIndex:[[_tableView indexPathForSelectedRow]row]];
BrouserViewController* bvc = [segue destinationViewController];
bvc.firstURL = selected.contentURL;
bvc.showingNews = selected;
bvc.showingSite = NULL;
selected.didRead = @(1);
}
#pragma mark UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [newsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
News* item = [newsArray objectAtIndex:indexPath.row];
if([item.didRead intValue] == 1){
cell.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
}else{
cell.backgroundColor = [UIColor whiteColor];
}
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
UIButton* button = (UIButton *)view;
[button addTarget:self action:@selector(onClickFavoriteButton:event:) forControlEvents:UIControlEventTouchUpInside];
if([item.favorite intValue] == 1){
button.selected = true;
}else{
button.selected = false;
}
}
break;
case 2:
{
UIButton* button = (UIButton *)view;
//メモボタン
[button addTarget:self action:@selector(onClickMemoButton:event:) forControlEvents:UIControlEventTouchUpInside];
if(item.memo == NULL || item.memo.contents.length <= 0){
button.imageView.image = [UIImage imageNamed:@"../memo.png"];
}else{
button.imageView.image = [UIImage imageNamed:@"../memo_blue.png"];
}
}
break;
case 3:
{
if(item.image != NULL && item.image.length >= 500){
UIImageView *imageView = (UIImageView*) view;
imageView.image = [UIImage imageWithData:item.image];
}else{
UIImageView *imageView = (UIImageView*) view;
imageView.image = [UIImage imageNamed:@"noimage.jpg"];
}
}
break;
case 4:
{
UILabel* textView = (UILabel*) view;
textView.text = item.title;
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
case 5:
{
UILabel* textView = (UILabel*) view;
textView.text = item.site.name;
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
case 6:
{
UILabel* textView = (UILabel*) view;
NSDate *date = [[item memo] updateDate];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd HH:mm"];
textView.text = [NSString stringWithFormat:@"メモ更新日時: %@",[formatter stringFromDate:date]];
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
default:
break;
}
}
return cell;
}
// ボタンタップ時に実行される処理
- (void)onClickFavoriteButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
//お気に入り追加
News *selected = [newsArray objectAtIndex:indexPath.row];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
if(view.class == [UIButton class]){
UIButton* button = (UIButton *)view;
if(button.tag == 1){
if([selected.favorite intValue] == 0){
[selected setFavorite:[NSNumber numberWithInt:1]];
button.selected = true;
}else{
[selected setFavorite:[NSNumber numberWithInt:0]];
button.selected = false;
}
}
}
}
}
// ボタンタップ時に実行される処理
- (void)onClickMemoButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
News *selected = [newsArray objectAtIndex:indexPath.row];
editingMemo = [selected memo];
if(editingMemo == NULL){
editingMemo = [NSEntityDescription insertNewObjectForEntityForName:@"Memo" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
editingMemo.news = selected;
selected.memo = editingMemo;
}
_textView.text = editingMemo.contents;
initialTextOfEditingMemo = editingMemo.contents;
[self fadeinMemoView];
}
// UIControlEventからタッチ位置のindexPathを取得する
- (NSIndexPath *)indexPathForControlEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint p = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
return indexPath;
}
- (IBAction)refreshButtonPressed:(id)sender
{
[self refresh];
}
- (IBAction)editDoneButtonPressed:(id)sender {
[_textView resignFirstResponder];
editingMemo.contents = _textView.text;
//データが変更されていれば更新日時を書き換え
if (![initialTextOfEditingMemo isEqualToString:[_textView text]]) {
// NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
// [outputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// NSLog([outputFormatter stringFromDate:[NSDate date]]);
// NSLog([outputFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:
// [[NSTimeZone systemTimeZone] secondsFromGMT]]]);
editingMemo.updateDate = [NSDate date];
}
[[ForUseCoreData getManagedObjectContext] save:NULL];
[self fadeOutMemoView];
[_tableView reloadData];
}
- (void) fadeinMemoView
{
//Viewを透明にする
[_backgroundView setAlpha:0.0];
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:1];
_backgroundView.hidden = NO;
_textView.hidden = NO;
_editDoneButton.hidden = NO;
// アニメーション終了
[UIView commitAnimations];
}
- (void) fadeOutMemoView
{
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:0];
// アニメーション終了
[UIView commitAnimations];
}
- (void) setNewsHavingMemo
{
//長さ1以上のメモを取得
NSArray* memoArray = [ForUseCoreData getAllMemoOrderByDate];
newsArray = [NSMutableArray array];
for (Memo* memo in memoArray) {
if([memo.news.site.unuse isEqual: @(0)])
[newsArray addObject:memo.news];
}
}
#pragma mark keyboardAction
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification*)aNotification
{
[_editDoneButton setFrame:CGRectMake(254.0, 100, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,140, 280, 200)];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
[_editDoneButton setFrame:CGRectMake(254.0, 144.0, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,182, 280, 267)];
}
@end
<file_sep>/GameMatome/GetAffURL.m
//
// GetAffURL.m
// GameMatome
//
// Created by <NAME> on 2014/08/23.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "GetAffURL.h"
#import "ForUseCoreData.h"
#import "Affs.h"
@implementation GetAffURL
- (id)init
{
self = [super init];
return self;
}
- (NSArray *)getAffs
{
affsArray = [NSMutableArray array];
//return affsArray;
//ローカルDBから削除
[ForUseCoreData deleteObjectsFromTable:@"Affs"];
//PHPファイルのURLを設定
NSString *url = @"http://wakuwakupark.main.jp/gamematome/getAffs.php";
//URLを指定してXMLパーサーを作成
NSURL *myURL = [NSURL URLWithString:url];
NSXMLParser *myParser = [[NSXMLParser alloc] initWithContentsOfURL:myURL];
myParser.delegate = self;
//xml解析開始
[myParser parse];
[[ForUseCoreData getManagedObjectContext]save:NULL];
return affsArray;
}
// ②XMLの解析
- (void)parserDidStartDocument:(NSXMLParser *)parser {
//解析中タグの初期化
nowTagStr = @"";
nowAff = NULL;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
//解析中タグに設定
nowTagStr = [NSString stringWithString:elementName];
if ([elementName isEqualToString:@"item"]) {
//テキストバッファの初期化
nowAff = [NSEntityDescription insertNewObjectForEntityForName:@"Affs" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[affsArray addObject:nowAff];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[nowAff setValue:string forKey:nowTagStr];
}
- (void)parser:(NSXMLParser *) parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
}
@end
<file_sep>/GameMatome/NewsViewController.h
//
// NewsViewController.h
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ChkControllerDelegate.h"
//@class Item;
@class Site;
@class News;
@class Memo;
@class GADBannerView;
@class ChkController;
@interface NewsViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate,ChkControllerDelegate,UIAlertViewDelegate>
{
NSArray* gamesArray; //ゲームエンティティが格納される配列
NSArray* newsArray; //ニュース配列
NSMutableArray* showingArray; //表示中の記事配列
//引っ張って更新
UIRefreshControl *_refreshControl;
Memo* editingMemo;
int mode; //0 test 1
GADBannerView* bannerView;
ChkController* chkController;
NSMutableArray* addArray;
NSArray* affArray;
NSString* initialTextOfEditingMemo;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *backgroundView;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIButton *editDoneButton;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
- (IBAction)refreshButtonPressed:(id)sender;
- (IBAction)editDoneButtonPressed:(id)sender;
- (IBAction)reviewButtonPressed:(id)sender;
@end
<file_sep>/GameMatome/Site.h
//
// Site.h
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Game;
@interface Site : NSManagedObject
@property (nonatomic, retain) NSNumber * favorite;
@property (nonatomic, retain) NSDate * lastUpdated;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * pageURL;
@property (nonatomic, retain) NSString * rssURL;
@property (nonatomic, retain) NSString * type;
@property (nonatomic, retain) NSNumber * unuse;
@property (nonatomic, retain) Game *game;
@property (nonatomic, retain) NSMutableSet *news;
@property (nonatomic, retain) NSNumber * siteId;
@end
@interface Site (CoreDataGeneratedAccessors)
- (void)addNewsObject:(NSManagedObject *)value;
- (void)removeNewsObject:(NSManagedObject *)value;
- (void)addNews:(NSSet *)values;
- (void)removeNews:(NSSet *)values;
- (void) changeUnuseState:(int)value;
@end
<file_sep>/GameMatome/GetUpdate.m
//
// GetUpdate.m
// GameMatome
//
// Created by <NAME> on 2014/08/14.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "GetUpdate.h"
@implementation GetUpdate
- (id)init
{
self = [super init];
return self;
}
- (NSDate*) returnUpdate
{
//PHPファイルのURLを設定
NSString *url = @"http://wakuwakupark.main.jp/gamematome/update.php";//ここにはそれぞれのPHPファイルのURLを指定して下さい
//URLを指定してXMLパーサーを作成
NSURL *myURL = [NSURL URLWithString:url];
NSXMLParser *myParser = [[NSXMLParser alloc] initWithContentsOfURL:myURL];
myParser.delegate = self;
//xml解析開始
[myParser parse];
NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd";
return [formatter dateFromString:dateString];
}
// ②XMLの解析
- (void)parserDidStartDocument:(NSXMLParser *)parser {
//解析中タグの初期化
nowTagStr = @"";
dateString=@"";
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
//解析中タグに設定
nowTagStr = [NSString stringWithString:elementName];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if([nowTagStr isEqualToString:@"lastupdate"])
dateString = string;
}
- (void)parser:(NSXMLParser *) parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
}
@end
<file_sep>/GameMatome/DetailSettingViewController.m
//
// DetailSettingViewController.m
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "DetailSettingViewController.h"
#import "Game.h"
#import "Site.h"
#import "ForUseCoreData.h"
#import "BrouserViewController.h"
#import "GADBannerView.h"
@interface DetailSettingViewController ()
@end
@implementation DetailSettingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//広告の設定
bannerView = [[GADBannerView alloc]initWithAdSize:kGADAdSizeBanner];
bannerView.adUnitID = @"ca-app-pub-9624460734614700/2538576676";
bannerView.rootViewController = self;
[self.view addSubview:bannerView];
[bannerView loadRequest:[GADRequest request]];
[bannerView setFrame:CGRectMake(0, 518, 320, 50)];
_tableView.delegate = self;
_tableView.dataSource = self;
_naviItem.title = _selectedGame.name;
sitesArray = [NSMutableArray array];
for(Site* s in [_selectedGame sites]){
[sitesArray addObject:s];
}
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillDisappear:(BOOL)animated
{
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
- (void)viewWillAppear:(BOOL)animated
{
[_tableView reloadData];
}
#pragma mark TableView
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
Site* site = [sitesArray objectAtIndex:indexPath.row];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag){
case 1:
{
UIButton* button = (UIButton *)view;
[button addTarget:self action:@selector(onClickUnuseButton:event:) forControlEvents:UIControlEventTouchUpInside];
if([[site unuse]integerValue] == 1){
button.selected = true;
button.titleLabel.textColor = [UIColor whiteColor];
button.backgroundColor = [UIColor lightGrayColor];
}else{
button.selected = false;
button.titleLabel.textColor = [UIColor whiteColor];
button.backgroundColor = [UIColor blueColor];
}
}
break;
case 2:
{
UILabel* label = (UILabel*)view;
label.text = [site name];
}
break;
}
}
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [sitesArray count];
}
// ボタンタップ時に実行される処理
- (void)onClickUnuseButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
//お気に入り追加
Site *selected = [sitesArray objectAtIndex:indexPath.row];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
if([[selected unuse]integerValue] == 1){
[selected changeUnuseState:0];
[_selectedGame setUnuse:@(0)];
}else{
[selected changeUnuseState:1];
}
}
break;
}
}
[_tableView reloadData];
}
// UIControlEventからタッチ位置のindexPathを取得する
- (NSIndexPath *)indexPathForControlEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint p = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
return indexPath;
}
#pragma mark 画面遷移
- (IBAction)doneButtonPressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
Site* selected = [sitesArray objectAtIndex:[[_tableView indexPathForSelectedRow] row]];
BrouserViewController* bvc = [segue destinationViewController];
bvc.firstURL = selected.pageURL;
bvc.showingNews = NULL;
bvc.showingSite = selected;
}
@end
<file_sep>/GameMatome/Parser.m
//
// Parser.m
// GameMatome
//
// Created by <NAME> on 2014/08/15.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "Parser.h"
#import "News.h"
#import "Site.h"
#import "ForUseCoreData.h"
@implementation Parser
- (id) init
{
self = [super init];
return self;
}
- (void)doParseWithSite:(Site*)site
{
rssSiteNumber = 0;
readingSite = site;
NSString* feed = [site rssURL];
NSURL *url = [NSURL URLWithString:feed];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
version = -1;
_parser = [[NSXMLParser alloc] initWithData:data];
_parser.delegate = self;
titleBuffer = NULL;
contentURLBuffer = NULL;
dateBuffer = NULL;
imgBuffer = NULL;
[_parser parse];
}
#pragma mark XMLParserDelegate
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
_elementName = elementName;
if ([_elementName isEqualToString:@"rdf:RDF"]) {
//rss 1.0
version = 1;
}else if ([_elementName isEqualToString:@"rss"]){
//rss 2.0
version = 2;
}
if(version == -1)
return;
switch (version) {
case 1:
//サイトデータ作成mode
if ([_elementName isEqualToString:@"channel"]){
checkingMode = 1;
//nowItem = NULL;
checkingNews = NULL;
}
//itemデータ作成mode
else if ([_elementName isEqualToString:@"item"]){
checkingMode = 2;
}
break;
case 2:
if ([_elementName isEqualToString:@"channel"]){
checkingMode = 1;
checkingNews = NULL;
}else if ([_elementName isEqualToString:@"item"]){
checkingMode = 2;
}
break;
default:
checkingMode = 0;
break;
}
}
- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
if(version == -1)
return;
if([string hasPrefix:@"\n"])
return;
switch (version) {
case 1:
switch (checkingMode) {
case 0:
break;
case 1:
if ([_elementName isEqualToString:@"title"]){
//RSSデータからサイトのタイトルを取得
//if([[readingSite name]isEqualToString:@"NoName"])
[readingSite setName:string];
}
break;
case 2:
if ([_elementName isEqualToString:@"title"]){
//nowItem.title = [NSString stringWithString:string];
//ニュースのタイトルを取得
titleBuffer = string;
}else if ([_elementName isEqualToString:@"link"]){
//コンテンツのURLを取得
contentURLBuffer = string;
}else if([_elementName isEqualToString:@"dc:date"]){
//更新時間を取得
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZ"];
dateBuffer = [dateFormatter dateFromString:string];
}else if([_elementName isEqualToString:@"content:encoded"]|| [_elementName isEqualToString:@"description"]){
//a href=" ~ " までを取り出す
NSArray *names = [string componentsSeparatedByString:@"a href=\""];
if ([names count] >= 2) {
NSArray* arr = [[names objectAtIndex:1] componentsSeparatedByString:@"\""];
NSString* imgURL = [arr objectAtIndex:0];
NSData *rowImgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
//画像をトリミング
UIImage* img = [self trimImage:[UIImage imageWithData:rowImgData] size:CGSizeMake(60,60)];
imgBuffer = [[NSData alloc] initWithData:UIImagePNGRepresentation( img )];
}
}
break;
default:
break;
}
break;
case 2:
switch (checkingMode) {
case 0:
break;
case 1:
if ([_elementName isEqualToString:@"title"]){
//サイトのタイトルを入力
//if([[readingSite name]isEqualToString:@"NoName"])
[readingSite setName:string];
}
break;
case 2:
if ([_elementName isEqualToString:@"title"]){
//ニュースのタイトルを設定
titleBuffer = string;
}else if ([_elementName isEqualToString:@"link"]){
//コンテンツのURLを設定
contentURLBuffer = string;
}else if([_elementName isEqualToString:@"dc:date"]||[_elementName isEqualToString:@"pubDate"]){
//更新日付を設定
//RSS2.0型変換
//Thu, 5 Jun 2014 16:41:56 +0900
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZZ"];
dateBuffer = [dateFormatter dateFromString:string];
}else if([_elementName isEqualToString:@"content:encoded"]|| [_elementName isEqualToString:@"description"]){
return;
//a href=" ~ " までを取り出す
NSArray *names = [string componentsSeparatedByString:@"a href=\""];
if ([names count] >= 2) {
NSArray* arr = [[names objectAtIndex:1] componentsSeparatedByString:@"\""];
NSString* imgURL = [arr objectAtIndex:0];
NSData *rowImgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
//画像をトリミング
UIImage* img = [self trimImage:[UIImage imageWithData:rowImgData] size:CGSizeMake(60,60)];
imgBuffer = [[NSData alloc] initWithData:UIImagePNGRepresentation( img )];
}
}
break;
default:
break;
}
break;
}
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if (version == -1) {
return;
}
switch (version) {
case 1:
if ([elementName isEqualToString:@"item"]){
checkingMode = 2;
//サイトの最終更新時間と比較して新しかったらエンティティを生成してデータを代入
if ([readingSite lastUpdated]== NULL || [[readingSite lastUpdated] compare:dateBuffer] == NSOrderedAscending) {
//未来のデータは無視
if([dateBuffer compare: [NSDate date]] == NSOrderedDescending){
return;
}
//新しいニュースエンティティを作成
checkingNews = [NSEntityDescription insertNewObjectForEntityForName:@"News" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[checkingNews setTitle:titleBuffer];
[checkingNews setContentURL:contentURLBuffer];
[checkingNews setImage:imgBuffer];
[checkingNews setDate:dateBuffer];
//サイトに追加
[[readingSite news] addObject:checkingNews];
[checkingNews setSite:readingSite];
//[readingSite setLastUpdated:[checkingNews date]];
titleBuffer = NULL;
contentURLBuffer = NULL;
dateBuffer = NULL;
imgBuffer = NULL;
}else{
[_parser abortParsing];
}
}
break;
case 2:
if ([elementName isEqualToString:@"item"]){
//サイトの最終更新時間と比較して新しかったらエンティティを生成してデータを代入
if ([readingSite lastUpdated]== NULL || [[readingSite lastUpdated] compare:dateBuffer] == NSOrderedAscending) {
//未来のデータは無視
if([dateBuffer compare: [NSDate date]] == NSOrderedDescending){
return;
}
//新しいニュースエンティティを作成
checkingNews = [NSEntityDescription insertNewObjectForEntityForName:@"News" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[checkingNews setTitle:titleBuffer];
[checkingNews setContentURL:contentURLBuffer];
[checkingNews setImage:imgBuffer];
[checkingNews setDate:dateBuffer];
//サイトに追加
[[readingSite news] addObject:checkingNews];
[checkingNews setSite:readingSite];
//[readingSite setLastUpdated:[checkingNews date]];
titleBuffer = NULL;
contentURLBuffer = NULL;
dateBuffer = NULL;
imgBuffer = NULL;
}else{
[_parser abortParsing];
}
}
break;
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
rssSiteNumber ++;
if (rssSiteNumber == 2) {
}
//NSLog(@"%@",[rssData description]);
}
- (UIImage *)trimImage:(UIImage *)imgOriginal size:(CGSize)size
{
UIGraphicsBeginImageContext(size);
// draw scaled image into thumbnail context
[imgOriginal drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newThumbnail = UIGraphicsGetImageFromCurrentImageContext();
// pop the context
UIGraphicsEndImageContext();
if(newThumbnail == nil)
NSLog(@"could not scale image");
return newThumbnail;
}
@end
<file_sep>/GameMatome/GetSiteList.m
//
// GetSiteList.m
// GameMatome
//
// Created by <NAME> on 2014/08/14.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "GetSiteList.h"
@implementation GetSiteList
- (id)init
{
self = [super init];
return self;
}
- (NSDictionary *)returnSiteArray
{
//ユーザ名格納配列 初期化
userArr = [NSMutableDictionary dictionary];
//PHPファイルのURLを設定
NSString *url = @"http://wakuwakupark.main.jp/gamematome/siteList.php";//ここにはそれぞれのPHPファイルのURLを指定して下さい
//URLを指定してXMLパーサーを作成
NSURL *myURL = [NSURL URLWithString:url];
NSXMLParser *myParser = [[NSXMLParser alloc] initWithContentsOfURL:myURL];
myParser.delegate = self;
//xml解析開始
[myParser parse];
return userArr;
}
// ②XMLの解析
- (void)parserDidStartDocument:(NSXMLParser *)parser {
//解析中タグの初期化
nowTagStr = @"";
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
//解析中タグに設定
nowTagStr = [NSString stringWithString:elementName];
if ([elementName isEqualToString:@"site_id"]) {
//テキストバッファの初期化
nowDic = [NSMutableDictionary dictionary];
NSString* key = [NSString stringWithFormat:@"%d",(int)[userArr count]];
[userArr setObject:nowDic forKey:key];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[nowDic setObject:string forKey:nowTagStr];
}
- (void)parser:(NSXMLParser *) parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
}
@end
<file_sep>/GameMatome/News.h
//
// News.h
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Memo, Site;
@interface News : NSManagedObject
@property (nonatomic, retain) NSString * contentURL;
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSData * image;
@property (nonatomic, retain) NSNumber * favorite;
@property (nonatomic, retain) NSNumber * didRead;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSNumber * unuse;
@property (nonatomic, retain) Site *site;
@property (nonatomic, retain) Memo *memo;
- (void) changeUnuseState:(int)value;
@end
<file_sep>/GameMatome/Site.m
//
// Site.m
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "Site.h"
#import "Game.h"
#import "News.h"
@implementation Site
@dynamic favorite;
@dynamic lastUpdated;
@dynamic name;
@dynamic pageURL;
@dynamic rssURL;
@dynamic type;
@dynamic unuse;
@dynamic game;
@dynamic news;
@dynamic siteId;
- (void) changeUnuseState:(int)value
{
[self setUnuse:@(value)];
for (News* n in [self news] ) {
[n changeUnuseState:value];
}
}
@end
<file_sep>/GameMatome/Affs.h
//
// Affs.h
// GameMatome
//
// Created by <NAME> on 2014/08/23.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Affs : NSManagedObject
@property (nonatomic, retain) NSString * affsId;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * url;
@property (nonatomic, retain) NSString * siteName;
@end
<file_sep>/GameMatome/SettingViewController.m
//
// SettingViewController.m
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "SettingViewController.h"
#import "ForUseCoreData.h"
#import "Game.h"
#import "DetailSettingViewController.h"
#import "GADBannerView.h"
@interface SettingViewController ()
@end
@implementation SettingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//広告の設定
bannerView = [[GADBannerView alloc]initWithAdSize:kGADAdSizeBanner];
bannerView.adUnitID = @"ca-app-pub-9624460734614700/2538576676";
bannerView.rootViewController = self;
[self.view addSubview:bannerView];
[bannerView loadRequest:[GADRequest request]];
[bannerView setFrame:CGRectMake(0, 470, 320, 50)];
gamesArray = [ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"];
_tableView.delegate = self;
_tableView.dataSource = self;
}
- (void)viewWillAppear:(BOOL)animated
{
[_tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillDisappear:(BOOL)animated
{
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
#pragma tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
Game* game = [gamesArray objectAtIndex:indexPath.row];
//cell.textLabel.text = [game name];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
UIButton* button = (UIButton *)view;
[button addTarget:self action:@selector(onClickUnuseButton:event:) forControlEvents:UIControlEventTouchUpInside];
if([[game unuse]integerValue] == 1){
button.selected = true;
button.titleLabel.textColor = [UIColor whiteColor];
button.backgroundColor = [UIColor lightGrayColor];
}else{
button.selected = false;
button.titleLabel.textColor = [UIColor whiteColor];
button.backgroundColor = [UIColor blueColor];
}
}
break;
case 2:
{
UILabel* label = (UILabel*)view;
label.text =[game name];
}
break;
}
}
//cell.textLabel.frame = CGRectMake(0, 0, 250, 60);
return cell;
}
// ボタンタップ時に実行される処理
- (void)onClickUnuseButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
//お気に入り追加
Game *selected = [gamesArray objectAtIndex:indexPath.row];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
if([[selected unuse]integerValue] == 1){
[selected changeUnuseState:0];
}else{
[selected changeUnuseState:1];
}
}
break;
}
}
[_tableView reloadData];
}
// UIControlEventからタッチ位置のindexPathを取得する
- (NSIndexPath *)indexPathForControlEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint p = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
return indexPath;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [gamesArray count];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
DetailSettingViewController* dvc = [segue destinationViewController];
Game* selected = [gamesArray objectAtIndex:[[_tableView indexPathForSelectedRow] row]];
[dvc setSelectedGame:selected];
}
- (IBAction)reviewButton:(id)sender {
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
NSString* url = [ud objectForKey:@"myituneURL"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
@end
<file_sep>/GameMatome/NewsViewController.m
//
// NewsViewController.m
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "NewsViewController.h"
#import "BrouserViewController.h"
#import "ForUseCoreData.h"
#import "Game.h"
#import "Site.h"
#import "News.h"
#import "Memo.h"
#import "Affs.h"
#import "GADBannerView.h"
#import "GetGameList.h"
#import "GetSiteList.h"
#import "GetUpdate.h"
#import "Parser.h"
#import "ChkController.h"
#import "GetAffURL.h"
#define MODE 1 // 0:local 1:web
#define MAX_NEWS_SIXE 300
#define FIRST_8CROPS 5
#define DIST_8CROPS 10
#define FIRST_FING 3
#define DIST_FING 6
@interface NewsViewController ()
@end
@implementation NewsViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_tableView.dataSource = self;
_tableView.delegate = self;
_backgroundView.hidden = YES;
_textView.hidden = YES;
_editDoneButton.hidden = YES;
_activityIndicator.hidden = YES;
//ゲームデータを収集
switch (MODE) {
case 0:
[self getSitesData];
break;
case 1:
[self setGameListWithDataBase];
break;
}
//
chkController = [[ChkController alloc]initWithDelegate:self];
[chkController requestDataList];
//RSSから読み取り
[self rssDataRead];
newsArray = [ForUseCoreData getAllNewsOrderByDate];
affArray = [[ForUseCoreData getEntityDataEntityNameWithEntityName:@"Affs"] mutableCopy];
_refreshControl = [[UIRefreshControl alloc] init];
[_refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
[_tableView addSubview:_refreshControl];
[self registerForKeyboardNotifications];
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
if([ud objectForKey:@"on"] == NULL){
[ud setObject:@"1" forKey:@"on"];
UIAlertView *alert =
[[UIAlertView alloc]
initWithTitle:@"お願い"
message:@"AppStore に\nレビューを書きませんか?"
delegate:self
cancelButtonTitle:@"キャンセル"
otherButtonTitles:@"レビュー", nil
];
[alert show];
}
}
- (void)viewWillDisappear:(BOOL)animated
{
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
- (void)viewDidAppear:(BOOL)animated
{
[self setshowingArrayWithAdds];
[_tableView reloadData];
}
- (void)getSitesData
{
//データを取得
gamesArray = [ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"];
//サイズ0ならplistから設定
if(gamesArray.count != 0){
NSLog(@"gamesArray Already Set");
return;
}
//データベースをリフレッシュ
[ForUseCoreData deleteAllObjects];
NSString* path = [[NSBundle mainBundle] pathForResource:@"SitesData" ofType:@"plist"];
NSDictionary *allDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
for (int i=0; i<[allDictionary count]; i++) {
NSString* key = [[allDictionary allKeys] objectAtIndex:i];
NSDictionary* dic = [allDictionary objectForKey:key];
Game* newGame = [NSEntityDescription insertNewObjectForEntityForName:@"Game" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[newGame setName:key];
[newGame setUnuse:false];
//サイト情報の取得
NSDictionary* sitesDic = [dic objectForKey:@"sites"];
if([sitesDic count]!=0){
//データを取得
for (int j=0; j<[sitesDic count]; j++) {
NSString* dataKey = [[sitesDic allKeys]objectAtIndex:j];
NSString* urlString = [sitesDic objectForKey:dataKey];
Site* newSite = [NSEntityDescription insertNewObjectForEntityForName:@"Site" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[newSite setGame:newGame];
[newSite setName:dataKey];
[newSite setPageURL:urlString];
//rssデータが存在するかチェック
NSString* rssString = [[dic objectForKey:@"rss"] objectForKey:dataKey];
if(rssString != NULL)
[newSite setRssURL:rssString];
else
[newSite setRssURL:NULL];
[newSite setType:dataKey];
}
}
}
//保存
[[ForUseCoreData getManagedObjectContext] save:NULL];
gamesArray = [ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"];
}
- (void)refresh
{
[_refreshControl endRefreshing];
switch (MODE) {
case 1:
[self setGameListWithDataBase];
break;
default:
break;
}
[self rssDataRead];
newsArray = [ForUseCoreData getAllNewsOrderByDate];
affArray = [[ForUseCoreData getEntityDataEntityNameWithEntityName:@"Affs"] mutableCopy];
[self setshowingArrayWithAdds];
[_tableView reloadData];
[_activityIndicator stopAnimating];
_backgroundView.hidden = YES;
_activityIndicator.hidden = YES;
}
- (void)endRefresh
{
[_refreshControl endRefreshing];
}
- (void)rssDataRead
{
//RSSの読み取り
//DOMツリー化
for(Game* game in gamesArray){
//不使用ならば次へ
if([[game unuse]isEqualToNumber:@(1)])
continue;
for (Site* site in [game sites]) {
//不使用ならば次へ
if([[site unuse]isEqualToNumber:@(1)])
continue;
//rssが設定されていなければNULL
if([site rssURL] == NULL)
continue;
//rssの最終更新日時を確認
//readingSite = site;
//[self rssDataReadOfSite:[site rssURL]];
Parser* parser = [[Parser alloc]init];
[parser doParseWithSite:site];
[site setLastUpdated: [NSDate date]];
}
}
//最大サイズを超えていたら削除
if([newsArray count]> MAX_NEWS_SIXE){
for (int i=MAX_NEWS_SIXE; i<[newsArray count]; i++) {
[[ForUseCoreData getManagedObjectContext]deleteObject:[newsArray objectAtIndex:i]];
}
}
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
#pragma mark UITableView Delegate
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
//対象インデックスのオブジェクトがnewsかbannarで分類
NSObject* selected = [showingArray objectAtIndex:[[_tableView indexPathForSelectedRow]row]];
if([selected isKindOfClass:[News class]]){
BrouserViewController* bvc = [segue destinationViewController];
bvc.firstURL = ((News *)selected).contentURL;
bvc.showingNews = (News *)selected;
bvc.showingSite = NULL;
((News *)selected).didRead = @(1);
}else if ([selected isKindOfClass:[ChkRecordData class]]){
BrouserViewController* bvc = [segue destinationViewController];
bvc.firstURL = ((ChkRecordData *)selected).linkUrl;
bvc.showingNews = NULL;
bvc.showingSite = NULL;
}else{
BrouserViewController* bvc = [segue destinationViewController];
bvc.firstURL = ((Affs *)selected).url;
bvc.showingNews = NULL;
bvc.showingSite = NULL;
bvc.buffer = ((Affs*)selected).title;
}
}
#pragma mark UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [showingArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
//News* item = [self getSelectedNewsWithMode:indexPath.row];
NSObject* selected = [showingArray objectAtIndex:indexPath.row];
if([selected isKindOfClass:[News class]]){
News* item = (News* )selected;
if([item.didRead intValue] == 1){
cell.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
}else{
cell.backgroundColor = [UIColor whiteColor];
}
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
UIButton* button = (UIButton *)view;
[button addTarget:self action:@selector(onClickFavoriteButton:event:) forControlEvents:UIControlEventTouchUpInside];
button.hidden = NO;
if([item.favorite intValue] == 1){
button.selected = true;
}else{
button.selected = false;
}
}
break;
case 2:
{
UIButton* button = (UIButton *)view;
button.hidden = NO;
if(item.memo == NULL || item.memo.contents.length <= 0){
button.imageView.image = [UIImage imageNamed:@"../memo.png"];
}else{
button.imageView.image = [UIImage imageNamed:@"../memo_blue.png"];
}
//メモボタン
[button addTarget:self action:@selector(onClickMemoButton:event:) forControlEvents:UIControlEventTouchUpInside];
}
break;
case 3:
{
}
break;
case 4:
{
UILabel* textView = (UILabel*) view;
textView.text = item.title;
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
case 5:
{
UILabel* textView = (UILabel*) view;
textView.text = item.site.name;
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
case 6:
{
UILabel* textView = (UILabel*) view;
NSDate *date = [item date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd HH:mm"];
textView.text = [formatter stringFromDate:date];
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
default:
break;
}
}
}else if ([selected isKindOfClass:[ChkRecordData class]]){
ChkRecordData* item = (ChkRecordData*)selected;
cell.backgroundColor = [UIColor whiteColor];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
UIButton* button = (UIButton *)view;
button.hidden = YES;
}
break;
case 2:
{
UIButton* button = (UIButton *)view;
//メモボタン
button.hidden = YES;
}
break;
case 3:
{
}
break;
case 4:
{
UILabel* textView = (UILabel*) view;
textView.text = [NSString stringWithFormat:@"【PR】 %@", item.description];
}
break;
case 5:
{
UILabel* textView = (UILabel*) view;
textView.text = item.title;
}
break;
case 6:
{
UILabel* textView = (UILabel*) view;
textView.text = @"";
}
break;
default:
break;
}
}
}else if([selected isKindOfClass:[Affs class]]){
Affs* item = (Affs*)selected;
cell.backgroundColor = [UIColor whiteColor];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
UIButton* button = (UIButton *)view;
button.hidden = NO;
}
break;
case 2:
{
UIButton* button = (UIButton *)view;
//メモボタン
button.hidden = NO;
}
break;
case 3:
{
}
break;
case 4:
{
UILabel* textView = (UILabel*) view;
textView.text = item.title;
}
break;
case 5:
{
UILabel* textView = (UILabel*) view;
textView.text = item.siteName;
}
break;
case 6:
{
UILabel* textView = (UILabel*) view;
textView.text = @"";
}
break;
default:
break;
}
}
}
return cell;
}
// ボタンタップ時に実行される処理
- (void)onClickFavoriteButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
//お気に入り追加
News *selected = [showingArray objectAtIndex :indexPath.row];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
if(view.class == [UIButton class]){
UIButton* button = (UIButton *)view;
if(button.tag == 1){
if([selected.favorite intValue] == 0){
[selected setFavorite:[NSNumber numberWithInt:1]];
button.selected = true;
}else{
[selected setFavorite:[NSNumber numberWithInt:0]];
button.selected = false;
}
}
}
}
}
// ボタンタップ時に実行される処理
- (void)onClickMemoButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
News *selected = [showingArray objectAtIndex :indexPath.row];
editingMemo = [selected memo];
if(editingMemo == NULL){
editingMemo = [NSEntityDescription insertNewObjectForEntityForName:@"Memo" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
editingMemo.news = selected;
selected.memo = editingMemo;
}
_textView.text = editingMemo.contents;
initialTextOfEditingMemo = editingMemo.contents;
[self fadeinMemoView];
}
// UIControlEventからタッチ位置のindexPathを取得する
- (NSIndexPath *)indexPathForControlEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint p = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
return indexPath;
}
- (IBAction)refreshButtonPressed:(id)sender
{
_backgroundView.hidden = NO;
_activityIndicator.hidden = NO;
[_activityIndicator startAnimating];
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
[self performSelector:@selector(refresh) withObject:nil afterDelay:0.1];
}
- (IBAction)editDoneButtonPressed:(id)sender {
[_textView resignFirstResponder];
editingMemo.contents = _textView.text;
//データが変更されていれば更新日時を書き換え
if (![initialTextOfEditingMemo isEqualToString:[_textView text]]) {
editingMemo.updateDate = [NSDate date];
}
[[ForUseCoreData getManagedObjectContext] save:NULL];
[self fadeOutMemoView];
[_tableView reloadData];
}
- (IBAction)reviewButtonPressed:(id)sender {
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
NSString* url = [ud objectForKey:@"myituneURL"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
- (void) fadeinMemoView
{
//Viewを透明にする
[_backgroundView setAlpha:0.0];
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:1];
_backgroundView.hidden = NO;
_textView.hidden = NO;
_editDoneButton.hidden = NO;
// アニメーション終了
[UIView commitAnimations];
}
- (void) fadeOutMemoView
{
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:0];
// アニメーション終了
[UIView commitAnimations];
}
- (void) setGameListWithDataBase
{
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
GetUpdate* gu = [[GetUpdate alloc]init];
if([ud objectForKey:@"lastUpdate"] != NULL){
NSDate* date = [ud objectForKey:@"lastUpdate"];
if([date compare:[gu returnUpdate]] != NSOrderedAscending){
gamesArray = [ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"];
return;
}
}
[ud setObject:[gu returnUpdate] forKey:@"lastUpdate"];
GetGameList* gg = [[GetGameList alloc]init];
GetSiteList* gs = [[GetSiteList alloc]init];
NSMutableArray* gamesBuffer = [[ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"] mutableCopy];
NSDictionary* dbGames = [gg returnGameArray];
NSDictionary* dbSites = [gs returnSiteArray];
for (NSDictionary* dic in [dbGames allValues]) {
BOOL flag = false;
for(Game* g in gamesBuffer){
if([g.gameId intValue] == [[dic objectForKey:@"id"]intValue]){
flag = true;
break;
}
}
if (!flag) {
Game* newGame = [NSEntityDescription insertNewObjectForEntityForName:@"Game" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[newGame setName:[dic objectForKey:@"name"]];
[newGame setGameId:[NSNumber numberWithInt:[[dic objectForKey:@"id"]intValue]]];
[newGame setUnuse:@(0)];
[gamesBuffer addObject:newGame];
}
}
NSMutableArray* siteBuffer = [[ForUseCoreData getEntityDataEntityNameWithEntityName:@"Site"] mutableCopy];
for (NSDictionary* dic in [dbSites allValues]) {
BOOL flag = false;
NSString* gameId = [dic objectForKey:@"game_id"];
NSString* siteId = [dic objectForKey:@"site_id"];
for (Site* s in siteBuffer) {
if([s.siteId intValue] == [siteId intValue]){
flag = true;
break;
}
}
if(!flag){
Site* site = [NSEntityDescription insertNewObjectForEntityForName:@"Site" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[site setName:[dic objectForKey:@"name"]];
[site setPageURL:[dic objectForKey:@"contentsURL"]];
[site setRssURL:[dic objectForKey:@"rssURL"]];
[site setSiteId:[NSNumber numberWithInt:[siteId intValue]]];
for (Game* g in gamesBuffer) {
if ([g.gameId intValue] == [gameId intValue]) {
[site setGame:g];
break;
}
}
}
}
[[ForUseCoreData getManagedObjectContext]save:NULL];
gamesArray = [ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"];
affArray = [NSArray array];
if([[ud objectForKey:@"test"] isEqualToString:@"0"]){
GetAffURL* ga = [[GetAffURL alloc]init];
affArray = [ga getAffs];
}
return;
}
#pragma mark keyboardAction
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification*)aNotification
{
[_editDoneButton setFrame:CGRectMake(254.0, 100, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,140, 280, 200)];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
[_editDoneButton setFrame:CGRectMake(254.0, 144.0, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,182, 280, 267)];
}
- (void) setshowingArrayWithAdds
{
showingArray = [newsArray mutableCopy];
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
if([[ud objectForKey:@"test"] isEqualToString:@"1"]){
return;
}
[self setShowingArrayWithAddArray:affArray First:FIRST_FING Distance:DIST_FING];
[self setShowingArrayWithAddArray:addArray First:FIRST_8CROPS Distance:DIST_8CROPS];
}
- (void) setShowingArrayWithAddArray:(NSArray*)adds First:(int)first Distance:(int)distance
{
int i=0;
NSMutableArray* buffer = [NSMutableArray array];
for(NSObject *news in showingArray){
if([buffer count]<first){
[buffer addObject:news];
}else{
if([buffer count] == first + i*distance){
if([adds count] > i){
[buffer addObject:[adds objectAtIndex:i]];
i++;
}
[buffer addObject:news];
}else{
[buffer addObject:news];
}
}
}
showingArray = buffer;
}
#pragma mark ChkControllerDelegate
- (void) chkControllerDataListWithSuccess:(NSDictionary*)data
{
addArray = [chkController dataList];
[self setshowingArrayWithAdds];
[_tableView reloadData];
}
- (void) chkControllerDataListWithError:(NSError *)error
{
}
- (void)chkControllerDataListWithNotFound:(NSDictionary *)data
{
}
#pragma mark UIAlertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
//レビューへ飛ばす
[self reviewButtonPressed:nil];
}
}
@end<file_sep>/GameMatome/GetSiteList.h
//
// GetSiteList.h
// GameMatome
//
// Created by <NAME> on 2014/08/14.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface GetSiteList : NSObject<NSXMLParserDelegate>
{
//xml解析で使用
NSString *nowTagStr;
NSString *txtBuffer;
//ユーザ名を格納する配列
NSMutableDictionary *userArr;
//
NSMutableDictionary* nowDic;
}
- (id)init;
- (NSDictionary*) returnSiteArray;
@end
<file_sep>/GameMatome/Affs.m
//
// Affs.m
// GameMatome
//
// Created by <NAME> on 2014/08/23.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "Affs.h"
@implementation Affs
@dynamic affsId;
@dynamic title;
@dynamic url;
@dynamic siteName;
@end
<file_sep>/GameMatome/BrouserViewController.m
//
// BrouserViewController.m
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "BrouserViewController.h"
#import "News.h"
#import "Memo.h"
#import "Site.h"
#import "Game.h"
#import "ForUseCoreData.h"
#import "GADBannerView.h"
@interface BrouserViewController ()
@end
@implementation BrouserViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//広告の設定
bannerView = [[GADBannerView alloc]initWithAdSize:kGADAdSizeBanner];
bannerView.adUnitID = @"ca-app-pub-9624460734614700/2398975874";
bannerView.rootViewController = self;
[self.view addSubview:bannerView];
[bannerView loadRequest:[GADRequest request]];
[bannerView setFrame:CGRectMake(0, 474, 320, 50)];
_editButton.enabled = YES;
if(_showingNews != NULL){
_naviItem.title = _showingNews.title;
}else{
if (_showingSite !=NULL) {
_naviItem.title = _showingSite.name;
}else{
_editButton.enabled = NO;
_naviItem.title = _buffer;
}
}
_doneButton.hidden = YES;
_textView.hidden = YES;
_backgroundView.hidden = YES;
_webView.delegate = self;
_backButton.enabled = NO;
_proceedButton.enabled = NO;
[self registerForKeyboardNotifications];
}
- (void)viewDidAppear:(BOOL)animated
{
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: _firstURL]]];
}
- (void)viewWillDisappear:(BOOL)animated
{
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)BackButtonPressed:(id)sender {
[_webView goBack];
}
- (IBAction)ProceedButtonPressed:(id)sender {
[_webView goForward];
}
- (IBAction)refreshButtonPressed:(id)sender {
[_webView reload];
}
- (IBAction)goBackListButtonPressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)noteButtonPressed:(id)sender {
_editingMemo = [_showingNews memo];
if(_editingMemo == NULL){
_editingMemo = (Memo*)[NSEntityDescription insertNewObjectForEntityForName:@"Memo" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
}
//データの読み込み
_textView.text = _editingMemo.contents;
initialTextOfEditingMemo = _editingMemo.contents;
//表示
[self fadeinMemoView];
}
- (IBAction)editDoneButtonPressed:(id)sender {
[_textView resignFirstResponder];
_editingMemo.contents = _textView.text;
_showingNews.memo = _editingMemo;
_editingMemo.news = _showingNews;
if(![initialTextOfEditingMemo isEqualToString:[_textView text]]){
_editingMemo.updateDate = [NSDate date];
}
[[ForUseCoreData getManagedObjectContext] save:NULL];
[self fadeOutMemoView];
}
- (IBAction)actionButtonPressed:(id)sender {
//アクションシートの生成と設定
UIActionSheet *sheet = [[UIActionSheet alloc] init];
//デリゲートをセット
sheet.delegate = self;
//タイトルとボタンの文言設定
[sheet addButtonWithTitle:@"Lineで共有"];
[sheet addButtonWithTitle:@"twitterで共有"];
[sheet addButtonWithTitle:@"Safariで開く"];
if(_showingNews != NULL){
[sheet addButtonWithTitle:@"お気に入りに追加"];
[sheet addButtonWithTitle:@"キャンセル"];
//キャンセルボタンをボタン3に設定
sheet.cancelButtonIndex = 4;
}else if (_showingSite != NULL){
if([[_showingSite unuse] integerValue] == 0){
[sheet addButtonWithTitle:@"購読しない"];
}else{
[sheet addButtonWithTitle:@"購読する"];
}
[sheet addButtonWithTitle:@"キャンセル"];
//キャンセルボタンをボタン3に設定
sheet.cancelButtonIndex = 4;
}else{
[sheet addButtonWithTitle:@"キャンセル"];
//キャンセルボタンをボタン3に設定
sheet.cancelButtonIndex = 3;
}
//アクションシートのスタイルを
sheet.actionSheetStyle = UIActionSheetStyleDefault;
//アクションシートを表示
[sheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 3:
//お気に入り追加/購読
if(_showingNews != NULL){
[[self showingNews] setFavorite:@(1)];
}else if(_showingSite != NULL){
if([[_showingSite unuse] integerValue] == 0){
[[self showingSite] changeUnuseState:1];
}else{
[[self showingSite] changeUnuseState:0];
[[[self showingSite] game] setUnuse:@(0)];
}
}
break;
case 0:
//facebook
[self sendLine];
break;
case 1:
//twitter
[self sendTwitter];
break;
case 2:
{
//safari
NSURL *url = [NSURL URLWithString:[_webView stringByEvaluatingJavaScriptFromString:@"document.URL"]];
[[UIApplication sharedApplication] openURL:url];
}
break;
}
}
- (void) fadeinMemoView
{
//Viewを透明にする
[_backgroundView setAlpha:0.0];
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:1];
_doneButton.hidden = NO;
_textView.hidden = NO;
_backgroundView.hidden = NO;
// アニメーション終了
[UIView commitAnimations];
}
- (void) fadeOutMemoView
{
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:0];
// アニメーション終了
[UIView commitAnimations];
}
- (void) sendLine
{
NSString *plainString = [NSString stringWithFormat:@"%@\n%@\n%@",[_naviItem title],[self urlForSend],[[NSUserDefaults standardUserDefaults] objectForKey:@"myituneURL"]];
NSString *contentKey = (__bridge NSString *)
CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)plainString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8 );
NSString *contentType = @"text";
NSString *urlString = [NSString
stringWithFormat: @"http://line.naver.jp/R/msg/%@/?%@",
contentType, contentKey];
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
}
- (void) sendFacebook
{
SLComposeViewController *facebookPostVC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
NSString* postContent = [_naviItem title];
[facebookPostVC setInitialText:postContent];
[facebookPostVC addURL:[NSURL URLWithString:[self urlForSend]]]; // URL文字列_
// [facebookPostVC addImage:[UIImage imageNamed:@"image_name_string"]]; // 画像名(文字列)
[self presentViewController:facebookPostVC animated:YES completion:nil];
}
- (void) sendTwitter
{
NSString* postContent = [_naviItem title];
NSURL* appURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"myituneURL"]];
// =========== iOSバージョンで、処理を分岐 ============
// iOS Version
NSString *iosVersion = [[[UIDevice currentDevice] systemVersion] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// Social.frameworkを使う
if ([iosVersion floatValue] >= 6.0) {
SLComposeViewController *twitterPostVC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[twitterPostVC setInitialText:postContent];
[twitterPostVC addURL:appURL]; // アプリURL
[self presentViewController:twitterPostVC animated:YES completion:nil];
}
// Twitter.frameworkを使う
else if ([iosVersion floatValue] >= 5.0) {
// Twitter画面を保持するViewControllerを作成する。
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
// 初期表示する文字列を指定する。
[twitter setInitialText:postContent];
// TweetにURLを追加することが出来ます。
[twitter addURL:appURL];
// Tweet後のコールバック処理を記述します。
// ブロックでの記載となり、引数にTweet結果が渡されます。
twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
if (res == TWTweetComposeViewControllerResultDone)
NSLog(@"tweet done.");
else if (res == TWTweetComposeViewControllerResultCancelled)
NSLog(@"tweet canceled.");
};
// Tweet画面を表示します。
[self presentModalViewController:twitter animated:YES];
}
}
- (NSString*) urlForSend
{
if(_showingNews == NULL){
return [_showingSite pageURL];
}else{
return [_showingNews contentURL];
}
}
#pragma mark webView
- (void)webViewDidStartLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
_backButton.enabled = [webView canGoBack];
_proceedButton.enabled = [webView canGoForward];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([error code] != NSURLErrorCancelled) {
NSString* errString = [NSString stringWithFormat:
@"<html><center><font size=+7 color='red'>通信エラー:<br>%@</font></center></html>",
error.localizedDescription];
[webView loadHTMLString:errString baseURL:nil];
}
}
#pragma mark keyboardAction
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification*)aNotification
{
[_doneButton setFrame:CGRectMake(254.0, 100, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,140, 280, 200)];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
[_doneButton setFrame:CGRectMake(254.0, 144.0, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,182, 280, 267)];
}
@end
<file_sep>/GameMatome/Memo.h
//
// Memo.h
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class News;
@interface Memo : NSManagedObject
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * contents;
@property (nonatomic, retain) NSDate * updateDate;
@property (nonatomic, retain) News *news;
@end
<file_sep>/GameMatome/Memo.m
//
// Memo.m
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "Memo.h"
#import "News.h"
@implementation Memo
@dynamic title;
@dynamic contents;
@dynamic updateDate;
@dynamic news;
@end
<file_sep>/GameMatome/FavoriteViewController.m
//
// FavoriteViewController.m
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "FavoriteViewController.h"
#import "BrouserViewController.h"
#import "ForUseCoreData.h"
#import "Game.h"
#import "Site.h"
#import "News.h"
#import "Memo.h"
#import "GADBannerView.h"
@interface FavoriteViewController ()
@end
@implementation FavoriteViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//広告の設定
bannerView = [[GADBannerView alloc]initWithAdSize:kGADAdSizeBanner];
bannerView.adUnitID = @"ca-app-pub-9624460734614700/2538576676";
bannerView.rootViewController = self;
[self.view addSubview:bannerView];
[bannerView loadRequest:[GADRequest request]];
[bannerView setFrame:CGRectMake(0, 470, 320, 50)];
_tableView.dataSource = self;
_tableView.delegate = self;
_backgroundView.hidden = YES;
_textView.hidden = YES;
_editDoneButton.hidden = YES;
// _refreshControl = [[UIRefreshControl alloc] init];
// [_refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
// [_tableView addSubview:_refreshControl];
[self registerForKeyboardNotifications];
}
- (void)viewWillDisappear:(BOOL)animated
{
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
- (void)viewDidAppear:(BOOL)animated
{
favoriteArray = [ForUseCoreData getFavoriteNewsOrderByDate];
[_tableView reloadData];
}
- (void)getSitesData
{
//データベースから取得
gamesArray = [ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"];
//サイズ0ならplistから設定
if(gamesArray.count != 0){
NSLog(@"gamesArray Already Set");
return;
}
//データベースをリフレッシュ
[ForUseCoreData deleteAllObjects];
NSString* path = [[NSBundle mainBundle] pathForResource:@"SitesData" ofType:@"plist"];
NSDictionary *allDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
for (int i=0; i<[allDictionary count]; i++) {
NSString* key = [[allDictionary allKeys] objectAtIndex:i];
NSDictionary* dic = [allDictionary objectForKey:key];
Game* newGame = [NSEntityDescription insertNewObjectForEntityForName:@"Game" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[newGame setName:key];
[newGame setUnuse:false];
//サイト情報の取得
NSDictionary* sitesDic = [dic objectForKey:@"sites"];
if([sitesDic count]!=0){
//データを取得
for (int j=0; j<[sitesDic count]; j++) {
NSString* dataKey = [[sitesDic allKeys]objectAtIndex:j];
NSString* urlString = [sitesDic objectForKey:dataKey];
Site* newSite = [NSEntityDescription insertNewObjectForEntityForName:@"Site" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[newSite setGame:newGame];
[newSite setName:dataKey];
[newSite setPageURL:urlString];
//rssデータが存在するかチェック
NSString* rssString = [[dic objectForKey:@"rss"] objectForKey:dataKey];
if(rssString != NULL)
[newSite setRssURL:rssString];
else
[newSite setRssURL:NULL];
[newSite setType:dataKey];
}
}
}
//保存
[[ForUseCoreData getManagedObjectContext] save:NULL];
gamesArray = [ForUseCoreData getEntityDataEntityNameWithEntityName:@"Game"];
}
- (void)refresh
{
[_refreshControl endRefreshing];
favoriteArray = [ForUseCoreData getFavoriteNewsOrderByDate];
[_tableView reloadData];
}
- (void)endRefresh
{
[_refreshControl endRefreshing];
}
- (void)rssDataRead
{
//RSSの読み取り
//DOMツリー化
rssSiteNumber = 0;
for(Game* game in gamesArray){
//不使用ならば次へ
if([[game unuse]isEqualToNumber:@(1)])
continue;
for (Site* site in [game sites]) {
//不使用ならば次へ
if([[site unuse]isEqualToNumber:@(1)])
continue;
//rssが設定されていなければNULL
if([site rssURL] == NULL)
continue;
//rssの最終更新日時を確認
readingSite = site;
[self rssDataReadOfSite:[site rssURL]];
[site setLastUpdated:[NSDate date]];
}
}
[[ForUseCoreData getManagedObjectContext] save:NULL];
}
- (void)rssDataReadOfSite:(NSString*) feed
{
NSURL *url = [NSURL URLWithString:feed];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
version = -1;
_parser = [[NSXMLParser alloc] initWithData:data];
_parser.delegate = self;
titleBuffer = NULL;
contentURLBuffer = NULL;
dateBuffer = NULL;
imgBuffer = NULL;
[_parser parse];
}
#pragma mark XMLParserDelegate
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
_elementName = elementName;
if ([_elementName isEqualToString:@"rdf:RDF"]) {
//rss 1.0
version = 1;
}else if ([_elementName isEqualToString:@"rss"]){
//rss 2.0
version = 2;
}
if(version == -1)
return;
switch (version) {
case 1:
//サイトデータ作成mode
if ([_elementName isEqualToString:@"channel"]){
checkingMode = 1;
//nowItem = NULL;
checkingNews = NULL;
}
//itemデータ作成mode
else if ([_elementName isEqualToString:@"item"]){
checkingMode = 2;
}
break;
case 2:
if ([_elementName isEqualToString:@"channel"]){
checkingMode = 1;
checkingNews = NULL;
}else if ([_elementName isEqualToString:@"item"]){
checkingMode = 2;
}
break;
default:
checkingMode = 0;
break;
}
}
- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
if(version == -1)
return;
if([string hasPrefix:@"\n"])
return;
switch (version) {
case 1:
switch (checkingMode) {
case 0:
break;
case 1:
if ([_elementName isEqualToString:@"title"]){
//RSSデータからサイトのタイトルを取得
//if([[readingSite name]isEqualToString:@"NoName"])
[readingSite setName:string];
}
break;
case 2:
if ([_elementName isEqualToString:@"title"]){
//nowItem.title = [NSString stringWithString:string];
//ニュースのタイトルを取得
titleBuffer = string;
}else if ([_elementName isEqualToString:@"link"]){
//コンテンツのURLを取得
contentURLBuffer = string;
}else if([_elementName isEqualToString:@"dc:date"]){
//更新時間を取得
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZ"];
dateBuffer = [dateFormatter dateFromString:string];
}else if([_elementName isEqualToString:@"content:encoded"]|| [_elementName isEqualToString:@"description"]){
//a href=" ~ " までを取り出す
NSArray *names = [string componentsSeparatedByString:@"a href=\""];
if ([names count] >= 2) {
NSArray* arr = [[names objectAtIndex:1] componentsSeparatedByString:@"\""];
NSString* imgURL = [arr objectAtIndex:0];
NSData *rowImgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
//画像をトリミング
UIImage* img = [self trimImage:[UIImage imageWithData:rowImgData] size:CGSizeMake(60,60)];
imgBuffer = [[NSData alloc] initWithData:UIImagePNGRepresentation( img )];
}
}
break;
default:
break;
}
break;
case 2:
switch (checkingMode) {
case 0:
break;
case 1:
if ([_elementName isEqualToString:@"title"]){
//サイトのタイトルを入力
//if([[readingSite name]isEqualToString:@"NoName"])
[readingSite setName:string];
}
break;
case 2:
if ([_elementName isEqualToString:@"title"]){
//ニュースのタイトルを設定
titleBuffer = string;
}else if ([_elementName isEqualToString:@"link"]){
//コンテンツのURLを設定
contentURLBuffer = string;
}else if([_elementName isEqualToString:@"dc:date"]||[_elementName isEqualToString:@"pubDate"]){
//更新日付を設定
//RSS2.0型変換
//Thu, 5 Jun 2014 16:41:56 +0900
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZZ"];
dateBuffer = [dateFormatter dateFromString:string];
}else if([_elementName isEqualToString:@"content:encoded"]|| [_elementName isEqualToString:@"description"]){
//a href=" ~ " までを取り出す
NSArray *names = [string componentsSeparatedByString:@"a href=\""];
if ([names count] >= 2) {
NSArray* arr = [[names objectAtIndex:1] componentsSeparatedByString:@"\""];
NSString* imgURL = [arr objectAtIndex:0];
NSData *rowImgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
//画像をトリミング
UIImage* img = [self trimImage:[UIImage imageWithData:rowImgData] size:CGSizeMake(60,60)];
imgBuffer = [[NSData alloc] initWithData:UIImagePNGRepresentation( img )];
}
}
break;
default:
break;
}
break;
}
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if (version == -1) {
return;
}
switch (version) {
case 1:
if ([elementName isEqualToString:@"item"]){
checkingMode = 2;
//サイトの最終更新時間と比較して新しかったらエンティティを生成してデータを代入
if ([readingSite lastUpdated]== NULL || [[readingSite lastUpdated] compare:dateBuffer] == NSOrderedAscending) {
//未来のデータは無視
if([dateBuffer compare:[NSDate date]] == NSOrderedDescending){
return;
}
//新しいニュースエンティティを作成
checkingNews = [NSEntityDescription insertNewObjectForEntityForName:@"News" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[checkingNews setTitle:titleBuffer];
[checkingNews setContentURL:contentURLBuffer];
[checkingNews setImage:imgBuffer];
[checkingNews setDate:dateBuffer];
//サイトに追加
[[readingSite news] addObject:checkingNews];
[checkingNews setSite:readingSite];
//[readingSite setLastUpdated:[checkingNews date]];
titleBuffer = NULL;
contentURLBuffer = NULL;
dateBuffer = NULL;
imgBuffer = NULL;
}else{
[_parser abortParsing];
}
}
break;
case 2:
if ([elementName isEqualToString:@"item"]){
//サイトの最終更新時間と比較して新しかったらエンティティを生成してデータを代入
if ([readingSite lastUpdated]== NULL || [[readingSite lastUpdated] compare:dateBuffer] == NSOrderedAscending) {
//未来のデータは無視
if([dateBuffer compare:[NSDate date]] == NSOrderedDescending){
return;
}
//新しいニュースエンティティを作成
checkingNews = [NSEntityDescription insertNewObjectForEntityForName:@"News" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
[checkingNews setTitle:titleBuffer];
[checkingNews setContentURL:contentURLBuffer];
[checkingNews setImage:imgBuffer];
[checkingNews setDate:dateBuffer];
//サイトに追加
[[readingSite news] addObject:checkingNews];
[checkingNews setSite:readingSite];
//[readingSite setLastUpdated:[checkingNews date]];
titleBuffer = NULL;
contentURLBuffer = NULL;
dateBuffer = NULL;
imgBuffer = NULL;
}else{
[_parser abortParsing];
}
}
break;
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
rssSiteNumber ++;
if (rssSiteNumber == 2) {
}
//NSLog(@"%@",[rssData description]);
}
#pragma mark UITableView Delegate
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
News* selected = [self getSelectedNewsWithMode:[[_tableView indexPathForSelectedRow] row]];
BrouserViewController* bvc = [segue destinationViewController];
bvc.firstURL = selected.contentURL;
bvc.showingNews = selected;
bvc.showingSite = NULL;
selected.didRead = @(1);
}
#pragma mark UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch ([self.tabBarController selectedIndex]) {
case 0:
return [newsArray count];
case 1:
return [favoriteArray count];
}
return [newsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
News* item = [self getSelectedNewsWithMode:indexPath.row];
if([item.didRead intValue] == 1){
cell.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
}else{
cell.backgroundColor = [UIColor whiteColor];
}
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
switch (view.tag) {
case 1:
{
UIButton* button = (UIButton *)view;
[button addTarget:self action:@selector(onClickFavoriteButton:event:) forControlEvents:UIControlEventTouchUpInside];
if([item.favorite intValue] == 1){
button.selected = true;
}else{
button.selected = false;
}
}
break;
case 2:
{
UIButton* button = (UIButton *)view;
//メモボタン
[button addTarget:self action:@selector(onClickMemoButton:event:) forControlEvents:UIControlEventTouchUpInside];
if(item.memo == NULL || item.memo.contents.length <= 0){
button.imageView.image = [UIImage imageNamed:@"../memo.png"];
}else{
button.imageView.image = [UIImage imageNamed:@"../memo_blue.png"];
}
}
break;
case 3:
{
if(item.image != NULL && item.image.length >= 500){
UIImageView *imageView = (UIImageView*) view;
imageView.image = [UIImage imageWithData:item.image];
}else{
UIImageView *imageView = (UIImageView*) view;
imageView.image = [UIImage imageNamed:@"noimage.jpg"];
}
}
break;
case 4:
{
UILabel* textView = (UILabel*) view;
textView.text = item.title;
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
case 5:
{
UILabel* textView = (UILabel*) view;
textView.text = item.site.name;
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
case 6:
{
UILabel* textView = (UILabel*) view;
NSDate *date = [item date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd HH:mm"];
textView.text = [formatter stringFromDate:date];
if([item.didRead intValue] == 1){
textView.textColor = [UIColor grayColor];
}else{
textView.textColor = [UIColor blackColor];
}
}
break;
default:
break;
}
}
return cell;
}
// ボタンタップ時に実行される処理
- (void)onClickFavoriteButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
//お気に入り追加
News *selected = [self getSelectedNewsWithMode:indexPath.row];
//各ボタンにイベントを設定
for(UIView* view in cell.contentView.subviews){
if(view.class == [UIButton class]){
UIButton* button = (UIButton *)view;
if(button.tag == 1){
if([selected.favorite intValue] == 0){
[selected setFavorite:[NSNumber numberWithInt:1]];
button.selected = true;
}else{
[selected setFavorite:[NSNumber numberWithInt:0]];
button.selected = false;
}
}
}
}
}
// ボタンタップ時に実行される処理
- (void)onClickMemoButton:(UIButton *)button event:(UIEvent *)event
{
// タップされたボタンから、対応するセルを取得する
NSIndexPath *indexPath = [self indexPathForControlEvent:event];
News *selected = [self getSelectedNewsWithMode:indexPath.row];
editingMemo = [selected memo];
if(editingMemo == NULL){
editingMemo = [NSEntityDescription insertNewObjectForEntityForName:@"Memo" inManagedObjectContext:[ForUseCoreData getManagedObjectContext]];
editingMemo.news = selected;
selected.memo = editingMemo;
}
_textView.text = editingMemo.contents;
initialTextOfEditingMemo = editingMemo.contents;
[self fadeinMemoView];
}
// UIControlEventからタッチ位置のindexPathを取得する
- (NSIndexPath *)indexPathForControlEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint p = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
return indexPath;
}
- (UIImage *)trimImage:(UIImage *)imgOriginal size:(CGSize)size
{
UIGraphicsBeginImageContext(size);
// draw scaled image into thumbnail context
[imgOriginal drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newThumbnail = UIGraphicsGetImageFromCurrentImageContext();
// pop the context
UIGraphicsEndImageContext();
if(newThumbnail == nil)
NSLog(@"could not scale image");
return newThumbnail;
}
- (IBAction)refreshButtonPressed:(id)sender
{
[self refresh];
}
- (IBAction)editDoneButtonPressed:(id)sender {
[_textView resignFirstResponder];
editingMemo.contents = _textView.text;
//データが変更されていれば更新日時を書き換え
if (![initialTextOfEditingMemo isEqualToString:[_textView text]]) {
editingMemo.updateDate = [NSDate date];
}
[[ForUseCoreData getManagedObjectContext] save:NULL];
[self fadeOutMemoView];
[_tableView reloadData];
}
- (void) fadeinMemoView
{
//Viewを透明にする
[_backgroundView setAlpha:0.0];
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:1];
_backgroundView.hidden = NO;
_textView.hidden = NO;
_editDoneButton.hidden = NO;
// アニメーション終了
[UIView commitAnimations];
}
- (void) fadeOutMemoView
{
// アニメーション
[UIView beginAnimations:nil context:NULL];
// 秒数設定
[UIView setAnimationDuration:0.2];
[_backgroundView setAlpha:0];
// アニメーション終了
[UIView commitAnimations];
}
- (News *) getSelectedNewsWithMode:(NSInteger)index
{
switch ([self.tabBarController selectedIndex]) {
case 0:
return [newsArray objectAtIndex:index];
case 1:
return [favoriteArray objectAtIndex:index];
default:
return [newsArray objectAtIndex:index];
}
}
#pragma mark keyboardAction
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification*)aNotification
{
[_editDoneButton setFrame:CGRectMake(254.0, 100, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,140, 280, 200)];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
[_editDoneButton setFrame:CGRectMake(254.0, 144.0, 46.0, 30.0)];
[_textView setFrame:CGRectMake(20,182, 280, 267)];
}
@end
<file_sep>/GameMatome/ForUseCoreData.m
//
// ForUseCoreData.m
// GameMatome
//
// Created by <NAME> on 2014/08/02.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "ForUseCoreData.h"
@implementation ForUseCoreData
static NSManagedObjectContext* managedObjectContext;
#define MODEL_NAME @"GameMatome"
#define DB_NAME @"GameMatome.splite"
+ (NSURL*)createStoreURL {
NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[directories lastObject] stringByAppendingPathComponent:DB_NAME];
NSURL *storeURL = [NSURL fileURLWithPath:path];
return storeURL;
}
+ (NSURL*)createModelURL {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *path = [mainBundle pathForResource:MODEL_NAME ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:path];
return modelURL;
}
+ (NSManagedObjectContext*)createManagedObjectContext {
NSURL *modelURL = [self createModelURL];
NSURL *storeURL = [self createStoreURL];
NSError *error = nil;
NSManagedObjectModel *managedObjectModel=[[NSManagedObjectModel alloc]initWithContentsOfURL:modelURL];
NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
[persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
NSManagedObjectContext *managedObjectContent = [[NSManagedObjectContext alloc] init];
[managedObjectContent setPersistentStoreCoordinator:persistentStoreCoordinator];
return managedObjectContent;
}
+ (void) setManagedObejctContext: (NSManagedObjectContext*) man{
managedObjectContext = man;
}
+ (NSManagedObjectContext*) getManagedObjectContext{
if(managedObjectContext == NULL)
managedObjectContext = [self createManagedObjectContext];
return managedObjectContext;
}
+ (NSArray *)getEntityDataEntityNameWithEntityName:(NSString *)entityName
{
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self getManagedObjectContext]];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
//取ってくるエンティティの設定を行う
[request setEntity:entity];
//比較対象を直接描くのがポイント
// NSPredicate *predicate =[NSPredicate predicateWithFormat:@"labelA == %@",searchString];
// [request setPredicate:predicate];
NSError *error = nil;
//データのフェッチを行う Data Fetching.
return [[self getManagedObjectContext] executeFetchRequest:request error:&error];
}
+(NSArray *)getEntityDataEntityNameWithEntityName:(NSString *)entityName condition:(NSString *)condition
{
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self getManagedObjectContext]];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
//取ってくるエンティティの設定を行う
[request setEntity:entity];
//比較対象を直接描く
NSPredicate *predicate =[NSPredicate predicateWithFormat:condition];
[request setPredicate:predicate];
NSError *error = nil;
//データのフェッチを行う Data Fetching.
return [[self getManagedObjectContext] executeFetchRequest:request error:&error];
}
+ (NSArray *)getAllNewsOrderByDate
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"News" inManagedObjectContext:[self getManagedObjectContext]];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
//取ってくるエンティティの設定を行う
[request setEntity:entity];
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"unuse==0"];
[request setPredicate:predicate];
//dateでソート
NSSortDescriptor *sortDesc =[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDesc]];
NSError *error = nil;
//データのフェッチを行う Data Fetching.
return [[self getManagedObjectContext] executeFetchRequest:request error:&error];
}
+ (NSArray *)getFavoriteNewsOrderByDate
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"News" inManagedObjectContext:[self getManagedObjectContext]];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
//取ってくるエンティティの設定を行う
[request setEntity:entity];
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"favorite==1&&unuse==0"];
[request setPredicate:predicate];
//dateでソート
NSSortDescriptor *sortDesc =[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDesc]];
NSError *error = nil;
//データのフェッチを行う Data Fetching.
return [[self getManagedObjectContext] executeFetchRequest:request error:&error];
}
+ (void)deleteObjectsFromTable:(NSString*) entity
{
//削除対象のフェッチ情報を生成
NSFetchRequest *deleteRequest = [[NSFetchRequest alloc] init];
[deleteRequest setEntity:[NSEntityDescription entityForName:entity inManagedObjectContext:managedObjectContext]];
[deleteRequest setIncludesPropertyValues:NO]; //managed object IDのみフェッチ
NSError *error = nil;
//生成したフェッチ情報からデータをフェッチ
NSArray *results = [managedObjectContext executeFetchRequest:deleteRequest error:&error];
//[deleteRequest release]; //ARCオフの場合
//フェッチしたデータを削除処理
for (NSManagedObject *data in results) {
[managedObjectContext deleteObject:data];
}
NSError *saveError = nil;
//削除を反映
[managedObjectContext save:&saveError];
}
+ (void)deleteAllObjects
{
[self deleteObjectsFromTable:@"Memo"];
[self deleteObjectsFromTable:@"News"];
[self deleteObjectsFromTable:@"Site"];
[self deleteObjectsFromTable:@"Game"];
}
+ (NSArray*)getAllMemoOrderByDate
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Memo" inManagedObjectContext:[self getManagedObjectContext]];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
//取ってくるエンティティの設定を行う
[request setEntity:entity];
//長さ1以上のみ取得
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"contents!=nil&&contents.length>=1"];
[request setPredicate:predicate];
//dateでソート
NSSortDescriptor *sortDesc =[NSSortDescriptor sortDescriptorWithKey:@"updateDate" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDesc]];
NSError *error = nil;
//データのフェッチを行う Data Fetching.
return [[self getManagedObjectContext] executeFetchRequest:request error:&error];
}
@end
<file_sep>/gamematome-network/getAffs.php
<?php
$link = mysql_connect("mysql016.phy.lolipop.lan", "LAA0523611", "h1yahag1");
if(!$link){
die('接続失敗です。'.mysql_error());
}
// MySQLに対する処理
$db_selected = mysql_select_db('LAA0523611-gamematome', $link);
if (!$db_selected){
die('データベース選択失敗です。'.mysql_error());
}
mysql_set_charset('utf8');
$result = mysql_query('SELECT * FROM affs');
if (!$result) {
die('クエリーが失敗しました。'.mysql_error());
}
header("Content-Type: text/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="utf-8"?>
<data>';
//user分ループして表示
while ($row = mysql_fetch_assoc($result) ) {
echo '<item>';
echo '<affsId>'.$row['affsId'].'</affsId>';
echo '<title>'.$row['title'].'</title>';
echo '<url>'.$row['url'].'</url>';
echo '<siteName>'.$row['siteName'].'</siteName>';
echo '</item>';
}
echo '</data>';
$close_flag = mysql_close($link);
?>
<file_sep>/GameMatome/Parser.h
//
// Parser.h
// GameMatome
//
// Created by <NAME> on 2014/08/15.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@class News;
@class Site;
@interface Parser : NSObject<NSXMLParserDelegate>
{
NSString* _elementName;
NSXMLParser *_parser;
int version;
int checkingMode;
int rssSiteNumber;
News* checkingNews;
Site* readingSite;
//パース用データバッファ
NSString* titleBuffer;
NSString* contentURLBuffer;
NSDate* dateBuffer;
NSData* imgBuffer;
}
- (id) init;
- (void) doParseWithSite:(Site*)site;
@end
<file_sep>/GameMatome/BrouserViewController.h
//
// BrouserViewController.h
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#import <Twitter/Twitter.h>
@class News;
@class Memo;
@class Site;
@class GADBannerView;
@interface BrouserViewController : UIViewController<UIActionSheetDelegate,UIWebViewDelegate>
{
GADBannerView* bannerView;
NSString* initialTextOfEditingMemo;
}
@property (nonatomic, retain) NSString* firstURL;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIButton *doneButton;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIView *backgroundView;
@property (nonatomic, retain) NSString * buffer;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *proceedButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *editButton;
@property (weak, nonatomic) IBOutlet UINavigationItem *naviItem;
@property (nonatomic, retain) News* showingNews;
@property (nonatomic, retain) Site* showingSite;
@property (nonatomic, retain) Memo* editingMemo;
- (IBAction)BackButtonPressed:(id)sender;
- (IBAction)ProceedButtonPressed:(id)sender;
- (IBAction)refreshButtonPressed:(id)sender;
- (IBAction)goBackListButtonPressed:(id)sender;
- (IBAction)noteButtonPressed:(id)sender;
- (IBAction)editDoneButtonPressed:(id)sender;
- (IBAction)actionButtonPressed:(id)sender;
@end
<file_sep>/GameMatome/DetailSettingViewController.h
//
// DetailSettingViewController.h
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@class Game;
@class GADBannerView;
@interface DetailSettingViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate>
{
NSMutableArray* sitesArray;
GADBannerView* bannerView;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, retain) Game* selectedGame;
@property (weak, nonatomic) IBOutlet UINavigationItem *naviItem;
- (IBAction)doneButtonPressed:(id)sender;
@end
<file_sep>/GameMatome/SettingViewController.h
//
// SettingViewController.h
// GameMatome
//
// Created by <NAME> on 2014/06/07.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@class GADBannerView;
@interface SettingViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
NSArray* gamesArray;
GADBannerView* bannerView;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)reviewButton:(id)sender;
@end
<file_sep>/DerivedData/GameMatome/Build/Products/Debug-iphoneos/GameMatome.app/SMPCM-ARC.embeddedframework/SMPCM.framework/Headers/SMPCMCore.h
//
// SMPCMCore.h
// SMPCMDemo
//
// Created by <NAME> on 2014/02/13.
// Copyright (c) 2014年 Link-U. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
SMPCM SDKの機能を呼び出すためのクラスです。
ARCにのみ対応しております。
アプリのインストール追跡や、サーバへ広告表示の成果通知の処理をすべて担います。
*/
@interface SMPCMCore : NSObject
/**
* 広告の表示モード
*/
typedef NS_ENUM(NSUInteger, SMPCMPlayerType) {
/**
* ポップアップで広告を表示します。
*/
SMPCMPlayerTypePopUp,
/**
* フルスクリーンで広告を表示します。動画がキャッシュされていない場合はポップアップで広告を表示します。
*/
SMPCMPlayerTypeFullscreen,
};
/**
SDKのバージョンを示す文字列を返します。
@return バージョンの文字列
*/
+ (NSString *)getVersionString;
/**
SDKによる処理を開始します。
@warning 起動時に広告を表示するに必ず呼び出さなければならなりません。デフォルトではポップアップで広告を表示します。
*/
+ (void)start;
/**
* SDKによる処理を開始します。
*
* @param type 広告の表示モードを指定します。
*/
+ (void)startWithPlayerType:(SMPCMPlayerType)type;
/**
保存するキャッシュの最大容量を設定します。
@warning 明示的に設定しない場合は、10MBがキャッシュの最大容量となります。
@param byte バイト数
*/
+ (void)setTotalFileSize:(NSInteger)byte;
/**
* キャッシュしているファイルをすべて削除します。
*/
+ (void)clearCache;
/**
メディアキーの設定をします。
@param mediaKey メディアキーの文字列
*/
+ (void)setMediaKey:(NSString *)mediaKey;
/**
* 全画面で動画広告を表示します。
*
* @param checkpoint 表示したタイミングの名前
*/
+ (void)showFullscreenView:(NSString *)checkpoint;
/**
ポップアップ広告を表示します。
@param checkpoint 表示したタイミングの名前
*/
+ (void)showPopUpView:(NSString *)checkpoint;
@end
<file_sep>/GameMatome/ForUseCoreData.h
//
// ForUseCoreData.h
// GameMatome
//
// Created by <NAME> on 2014/08/02.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <sqlite3.h>
@class Game;
@class Site;
@class News;
@class Memo;
@interface ForUseCoreData : NSObject
{
}
+ (void) setManagedObejctContext: (NSManagedObjectContext*) man;
+ (NSManagedObjectContext*) getManagedObjectContext;
+ (NSArray*) getEntityDataEntityNameWithEntityName:(NSString*)entityName;
+ (NSArray*) getEntityDataEntityNameWithEntityName:(NSString*)entityName condition:(NSString*)condition;
+ (NSArray*) getAllNewsOrderByDate;
+ (NSArray*) getFavoriteNewsOrderByDate;
+ (NSArray*) getAllMemoOrderByDate;
+ (void) deleteAllObjects;
+ (void) deleteObjectsFromTable:(NSString*) entity;
@end
<file_sep>/gamematome-network/getURL.php
<?php
$link = mysql_connect("mysql016.phy.lolipop.lan", "LAA0523611", "h1yahag1");
if(!$link){
die('接続失敗です。'.mysql_error());
}
// MySQLに対する処理
$db_selected = mysql_select_db('LAA0523611-gamematome', $link);
if (!$db_selected){
die('データベース選択失敗です。'.mysql_error());
}
mysql_set_charset('utf8');
$result = mysql_query('SELECT * FROM url_table');
if (!$result) {
die('クエリーが失敗しました。'.mysql_error());
}
//user分ループして表示
while ($row = mysql_fetch_assoc($result) ) {
echo $row['url'];
}
$close_flag = mysql_close($link);
?>
<file_sep>/GameMatome/GetUpdate.h
//
// GetUpdate.h
// GameMatome
//
// Created by <NAME> on 2014/08/14.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface GetUpdate : NSObject<NSXMLParserDelegate>
{
//xml解析で使用
NSString *nowTagStr;
NSString *txtBuffer;
//
NSString* dateString;
}
- (id)init;
- (NSDate*) returnUpdate;
@end
<file_sep>/GameMatome/Game.h
//
// Game.h
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Game : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * unuse;
@property (nonatomic, retain) NSMutableSet *sites;
@property (nonatomic, retain) NSNumber *gameId;
@end
@interface Game (CoreDataGeneratedAccessors)
- (void)addSitesObject:(NSManagedObject *)value;
- (void)removeSitesObject:(NSManagedObject *)value;
- (void)addSites:(NSSet *)values;
- (void)removeSites:(NSSet *)values;
- (void) changeUnuseState:(int)value;
@end
<file_sep>/GameMatome/News.m
//
// News.m
// GameMatome
//
// Created by <NAME> on 2014/08/10.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import "News.h"
#import "Memo.h"
#import "Site.h"
@implementation News
@dynamic contentURL;
@dynamic date;
@dynamic image;
@dynamic favorite;
@dynamic didRead;
@dynamic title;
@dynamic unuse;
@dynamic site;
@dynamic memo;
- (void) changeUnuseState:(int)value
{
[self setUnuse:@(value)];
}
@end
<file_sep>/GameMatome/GetAffURL.h
//
// GetAffURL.h
// GameMatome
//
// Created by <NAME> on 2014/08/23.
// Copyright (c) 2014年 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@class Affs;
@interface GetAffURL : NSObject<NSXMLParserDelegate>
{
NSString* nowTagStr;
NSString *txtBuffer;
Affs* nowAff;
NSMutableArray* affsArray;
}
- (id) init;
- (NSArray*) getAffs;
@end
|
dde106f68c7c412543f532f2e253631ca66e370c
|
[
"Objective-C",
"PHP"
] | 34 |
Objective-C
|
wakuwakupark/gamematome
|
77892871d416328c5c326a5357a53d634bbe50af
|
df03d19f6e9740f7f7e9cb459c50da3752e0a968
|
refs/heads/master
|
<repo_name>ChristianSauer/jobdeleteexample<file_sep>/JobDeleteExample/DeleterService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.ResponseCaching.Internal;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Auth;
using Microsoft.Azure.Batch.Common;
using Microsoft.Extensions.Hosting;
namespace JobDeleteExample
{
public class DeleterService: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var accountUrl = "***";
var accountName = "***";
var accountSecret = "**";
var jobtoDelete = "as_1bf795a45fda4ad8ab0f79bc24a942eb";
var sharedKeyCredentials = new BatchSharedKeyCredentials(accountUrl, accountName, accountSecret);
var imageReference = new ImageReference(
publisher: "microsoft-azure-batch",
offer: "ubuntu-server-container",
sku: "16-04-lts",
version: "latest");
var virtualMachineConfiguration = new VirtualMachineConfiguration(
imageReference,
"batch.node.ubuntu 16.04");
using (var bc = await BatchClient.OpenAsync(sharedKeyCredentials))
{
try
{
var newJob = bc.JobOperations.CreateJob("test", new PoolInformation()
{
AutoPoolSpecification = new AutoPoolSpecification()
{
AutoPoolIdPrefix = "test",
PoolLifetimeOption = PoolLifetimeOption.Job,
KeepAlive = false,
PoolSpecification = new PoolSpecification()
{
TargetDedicatedComputeNodes = 1,
VirtualMachineSize = "Standard_A1_v2",
VirtualMachineConfiguration = virtualMachineConfiguration
},
}
});
newJob.Commit();
// never works fails with forbidden
await bc.JobOperations.DeleteJobAsync(newJob.Id, cancellationToken: stoppingToken);
}
catch (Exception e)
{
Console.WriteLine($"Could not delete the job because {e}");
throw;
}
Console.WriteLine("Could delete job!");
}
}
}
}
<file_sep>/JobDeleteExample/Dockerfile
FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 64055
EXPOSE 44384
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY JobDeleteExample/JobDeleteExample.csproj JobDeleteExample/
RUN dotnet restore JobDeleteExample/JobDeleteExample.csproj
COPY . .
WORKDIR /src/JobDeleteExample
RUN dotnet build JobDeleteExample.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish JobDeleteExample.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "JobDeleteExample.dll"]
|
3fdc3616c6dfaa4f8c3efe5a89fc197f3005285b
|
[
"C#",
"Dockerfile"
] | 2 |
C#
|
ChristianSauer/jobdeleteexample
|
9ba300936c60855b702e8bfebae2a4e9ee96934c
|
0f045000be18ee9766bcbfe045168c5ccb3c01d2
|
refs/heads/master
|
<file_sep>node[:deploy].each do |app_name, deploy|
include_recipe 'deploy::default'
script "deploy_clean" do
interpreter "bash"
user "root"
line = 9
code <<-EOH
sed -i "#{line}i ShibUseHeaders On" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i SetHandler shib" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i Require shibboleth" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i ShibRequireSession Off" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i AuthType shibboleth" /etc/apache2/sites-available/#{app_name}.conf
service apache2 restart
EOH
end
script "deploy_clean_https" do
if node[:deploy][app_name][:ssl_support]
interpreter "bash"
user "root"
line = 69
code <<-EOH
sed -i "#{line}i ShibUseHeaders On" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i SetHandler shib" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i Require shibboleth" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i ShibRequireSession Off" /etc/apache2/sites-available/#{app_name}.conf
sed -i "#{line}i AuthType shibboleth" /etc/apache2/sites-available/#{app_name}.conf
service apache2 restart
EOH
end
end
template "shibboleth2" do
source "shibboleth2.xml.erb"
path "/etc/shibboleth/shibboleth2.xml"
variables(node['shib'])
end
template "shibboleth2-ssl-key" do
mode 0644
source 'ssl.key.erb'
path "/etc/shibboleth/sp-key.pem"
end
template "shibboleth2-ssl-cert" do
mode 0644
source 'ssl.cert.erb'
path "/etc/shibboleth/sp-cert.pem"
end
script "deploy_shibd" do
interpreter "bash"
user "root"
code <<-EOH
sudo service apache2 restart
sudo service shibd restart
EOH
end
end
<file_sep>node[:deploy].each do |app_name, deploy|
cron "index_users" do
minute "*/5"
command "wget -q http://#{node[:opsworks][:instance][:ip]}/welcome?index_users"
end
cron "index_curations" do
minute "*/5"
command "wget -q http://#{node[:opsworks][:instance][:ip]}/welcome?index_curations"
end
cron "optimize_index" do
minute "*/12"
command "wget -q http://#{node[:opsworks][:instance][:ip]}/welcome?optimize_index"
end
end
|
6c3cea45de7f0325de6cd3ba2862d53477a22ed5
|
[
"Ruby"
] | 2 |
Ruby
|
alyahmmed/cookbooks
|
5d922b24e5951f0b00ae4434ae0dfe1df0938347
|
db7ec63b8074ca6a56b89947002677ffaf353630
|
refs/heads/master
|
<file_sep>
# Deploy a Flask Web application on a linux server
<img src="img/CatalogApp.png"
alt="CatalogApp screenshot"
width=640px; />
URL: [thecatalogproject.org](https://thecatalogproject.org)
Server public IP: 192.168.127.12
## Table of Contents
+ [Description](#description)
+ [Requirements](#requirements)
+ [Setup](#setup)
+ [Linux Server](#linux-server)
+ [PostgreSQL](#postgresql)
+ [Deploy Application](#deploy-application)
+ [CatalogApp](#catalogapp)
+ [Python environment](#python-environment)
+ [Apache HTTP](#apache-http)
+ [SSL](#ssl)
+ [License](#license)
## Description
This project is a part of Udacity Full Stack Web Developer Nanodegree program. In this project we are going to deploy [**CatalogApp**](https://github.com/olegoseev/CatalogApp) Flask application on publicly accessible linux server. Original [**CatalogApp**](https://github.com/olegoseev/CatalogApp) was storing data in the [**SQLite**](https://www.sqlite.org/index.html) database. In this project we are going to use [**PostgreSQL**](https://www.postgresql.org/) as a data storage.
## Requirements
Software being used in this project:
+ Linux server: Ubuntu 16.04 Xenial on [Amazon EC2 web service](https://aws.amazon.com/ec2/)
+ [Apache2 HTTP server](https://httpd.apache.org/)
+ [PostgreSQL](https://www.postgresql.org/)
+ [Python > 3.5](https://www.python.org/)
+ Python modules
+ [Flask (a python micro-framework)](http://flask.pocoo.org/)
+ flask_httpauth
+ [SqlAlchemy (SQL/ORM tool)](http://www.sqlalchemy.org/)
+ passlib
+ requests
+ httplib2
+ oauth2clinet
+ [psycopg2-binary (PostgreSQL Adapter)](http://initd.org/psycopg/)
[(back to top)](#deploy-a-flask-web-application-on-a-linux-server)
## Setup
### Linux server
For this project I choose Ubuntu 16.04 Xenial t2.micro instance on Amazon EC2 web service to host _CatalogApp_ web application. After the instance was launched following steps were taken to configure the server and make it ready to host our application:
+ #### Update all currently installed packages
```
sudo apt-get update
sudo apt-get upgrade
```
Set timezone to UTC. In opened window select _**None of the above**_ then find UTC
```
sudo dpkg-reconfigure tzdata
```
Install pip for Python3
```
sudo apt-get install python3-ip
```
+ #### Install Apache HTTP server
```
sudo apt-get install apache2
```
Since we are using Python3, we need to install Python3 mod_wsgi package
```
sudo apt-get install libapache2-mod-wsgi-py3
```
Enable mod_wsgi. WSGI (Web Server Gateway Interface) is an interface between web servers and web apps for python. mod_wsgi is an Apache HTTP server mod that enables Apache to serve Flask applications
```
sudo a2emod wsgi
```
+ #### Change the SSH port from 22 to 2200
Configure AWS instance security group inbound rules as follow:

Login in the instance and change default ssh port, edit configuration file:
```
$sudo nano /etc/ssh/sshd_config
```
Locate the following line:
```
Port 22
```
Change default port number from 22 to 2200 and disable root login
```
# Authentication:
PermitRootLogin no
```
Restart the ssh service to activate changes
```
$sudo service sshd restart
```
+ #### Configure and enable firewall to secure the server
For security reason allow only outgoing traffic
```
sudo ufw default deny incoming
sudo ufw default allow outgoing
```
Open only ports for SSH(2200), HTTP/HTTPS and NTP services
```
sudo ufw allow 2200/tcp
sudo ufw allow http
sudo ufw allow https
sudo ufw allow 123/tcp
```
Enable firewall
```
sudo ufw enable
```
From now on use port 2200 when ssh to the instance
+ #### Create a new user
Add user named _**grader**_ to the server and give it _**sudo**_ privilege
```
sudo adduser grader
sudo usermod -aG sudo grader
```
In order to let run _sudo_ command without enter the password created a file named _grader_ in _/etc/sudoers.d_ with following content:
```
grader ALL=(ALL) NOPASSWD:ALL
```
Generate SSH key pair, so the user can log in to the server
```
ssh-keygen -t rsa -C "<EMAIL>"
```
Add the public key to the _**authorized_key**_ file
```
su grader
cd ~/
mkdir .ssh
touch .ssh/authorized_keys
nano .ssh/authorized_keys
```
Copy contents of the public key to authorized_keys file. Set file permissions with following commands:
```
chmod 600 .ssh/authorized_keys
chmod 700 .ssh
```
[(back to top)](#deploy-a-flask-web-application-on-a-linux-server)
### PostgreSQL
Ubuntu default repositories contain Postgres packages, so it can be installed using the apt packaging system
```
sudo apt-get update
sudo apt-get install postgresql postgresql-contrib
```
+ #### Create a new user and the database that will be used as a storage
Switch to postgres account and launch psql tool
```
sudo -i u postgres
psql
```
Create user and database
```sql
CREATE USER catalog WITH PASSWORD '<PASSWORD>';
CREATE DATABASE catalog WITH OWNER catalog;
REVOKE ALL ON SCHEMA public FROM public;
GRANT ALL ON SCHEMA public TO catalog;
```
Since user _catalog_ is not a linux user we need to add it into _pg_hba.conf_ file, so _catalog_ can connect to the database
```
sudo nano /etc/postgresql/9.5/main/pg_hba.conf
```
Add a following record
```
# TYPE DATABASE USER ADDRESS METHOD
local catalog catalog md5
```
[(back to top)](#deploy-a-flask-web-application-on-a-linux-server)
## Deploy application
### CatalogApp
In this step we will create directory structure for the application in and setup Python virtual environment.
Directory structure will be looking like this:
```
/var
|....www
|.......catalog
|..............venv
|..............app
|.................static
|.................templates
```
+ #### CatalogApp working directory
Navigate to the /var/www directory
```
cd /var/www
```
Create application directory named _catalog_
```
sudo mkdir catalog
```
In this directory we will keep wsgi file, python virtual environment and the application itself in its own directory
+ #### Clone CatalogApp repository
Clone CatalogApp repository to _app_ directory inside of the _catalog_ directory
```
sudo git clone git://github.com/olegoseev/CatalogApp.git app
```
Take the ownership of _catalog_ directory.
```
chown ubuntu:ubuntu /var/www/catalog
```
+ #### Configure CatalogApp
Navigate in /var/www/catalog/app directory. In files _catalogapp.py_ , _database_setup.py_ and _catalog_setup.py_
find following:
```python
engine = create_engine('sqlite:///catalog.db')
```
and replace with
```python
engine = create_engine('postgresql+psycopg2://catalog:c@t@l0g@localhost/catalog')
```
In file _catalogapp.py_ find lines of code where facebook and google client keys are loaded and add a full path to the files like below:
```python
G_CLIENT_ID = json.loads(
open('/var/www/catalog/app/google_client_secret.json', 'r').read())['web']['client_id']
FB_APP_ID = json.loads(
open('/var/www/catalog/app/fb_client_secret.json', 'r').read())['web']['app_id']
FB_APP_SECRET = json.loads(
open('/var/www/catalog/app/fb_client_secret.json', 'r').read())['web']['app_secret']
.
.
.
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets(
'/var/www/catalog/app/google_client_secret.json',
scope='')
```
+ #### Setup the database
We have installed PostgreSQL, created user and database. Now we are going to create tables and add some sample records in it. To create tables, execute following command:
```python
python3 /var/www/catalog/app/database_setup.py
```
To add sample records, issue the following command:
```python
python3 /var/www/catalog/app/catalog_setup.py
```
[(back to top)](#deploy-a-flask-web-application-on-a-linux-server)
### Python environment
Setting up a virtual environment will keep the application and its dependencies isolated from the main system
+ #### Setup Python virtual environment
Navigate in _catalog_ directory
```
cd /var/www/catalog
```
Install _virtualenv_ using following command
```
sudo pip3 install virtualenv
```
Create virtual environment
```
virtualenv venv
```
As a result a new directory called _venv_ will be created
Activate the virtual environment
```
source venv/bin/activate
```
Now it is time to install Python packages needed to run our application. While the virtual environment is active all the Python packages will be installed in it.
**Note:** command _sudo pip3 install [package]_ will install Python package globally. In order to install packages inside of the virtual environment we need to use _pip install [package]_ without _sudo_.
```
pip3 install flask
pip3 install sqlalchemy
pip3 install requests
pip3 install passlib
pip3 install flask_httpauth
pip3 install oauth2client
pip3 install httplib2
pip3 install psycopg2-binary
```
Deactivate the virtual environment
```
deactivate
```
[(back to top)](#deploy-a-flask-web-application-on-a-linux-server)
### Apache HTTP
+ #### Configure and Enable a New Virtual Host
Create a new virtual host configuration file by executing following command:
```
sudo nano /etc/apache2/sites-available/catalog.conf
```
Add the following lines of code to the file to configure the virtual host
```xml
<VirtualHost *:80>
ServerName thecatalogproject.org
ServerAdmin <EMAIL>
WSGIScriptAlias / /var/www/catalog/catalog.wsgi
<Directory /var/www/catalog/app/>
WSGIProcessGroup application
WSGIApplicationGroup %{GLOBAL}
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/catalog/app/static
<Directory /var/www/catalog/app/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
```
Save and close the file. Enable the virtual host with the following command
```
sudo a2ensite catalog
```
disable default host
```
sudo a2dissite default
```
+ #### Create wsgi file
Apache uses the .wsgi file to serve the Flask application. Navigate to the folder _catalog_ and create a file named _catalog.wsgi_ with following command:
```
sudo nano catalog.wsgi
```
Add following lines of code to the _catalog.wsgi_ file:
```python
#!/usr/bin/python3
import os, sys
import logging
import json
logging.basicConfig(stream=sys.stderr)
# following commands activate Python virtual environment
activate_this = '/var/www/catalog/venv/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
# add a path to the application
sys.path.insert(0, '/var/www/catalog/app')
# use google client Id as the application secret key
G_CLIENT_ID = json.loads(
open('/var/www/catalog/app/google_client_secret.json', 'r').read())['web']['client_id']
from catalogapp import app as application
application.secret_key = G_CLIENT_ID
```
Save and close the file.
Restart Apache HTTP server to launch the application with following command:
```
sudo service apache2 restart
```
Now we should be able to access to the application via a browser using the instance public IP
[(back to top)](#deploy-a-flask-web-application-on-a-linux-server)
## SSL
At this point we have successfully deployed CatalogApp on Amazon Web Service. The application is accessible via the browser using HTTP protocol. The major downside of it is that Facebook login api will not work. Facebook authentication api dropped support authentication requests coming from websites without SSL encryption. In order to enable SSL for our web application we need to register a domain name. To register a new domain we are going to use AWS Route 53 DNS. For this project I registered _thecatalogproject.org_ domain name.
To obtain SSL certificate for a newly registered domain name we used [**cerbot**](https://certbot.eff.org/lets-encrypt/ubuntuxenial-apache). Cerbot enables HTTPS on the website deploying Let's Encrypt certificates.
Since HTTPS protocol uses port 443, HTTP port 80 needs to be disables in the server firewall and AWS instance security group
## License
This project is licensed under the terms of the MIT license.
[(back to top)](#deploy-a-flask-web-application-on-a-linux-server)
|
eca1f70d6b9d53350e6db4909d2517bd23ff096c
|
[
"Markdown"
] | 1 |
Markdown
|
olegoseev/udacity-catalogapp-project
|
94a030b3ee22d8d81e097a6faaf15cc61898887b
|
232b02c35d571b614680290804d4a75da2474448
|
refs/heads/master
|
<repo_name>hasnell/DesignPatterns<file_sep>/Troll.java
package csce247.assignments.strategy;
//<NAME> csce 247
//creates troll character
public class Troll extends Character {
public Troll(String name) {
super(name);
//sets weapon to axe
weaponbehavior = new WeaponAxe();
}
//displays troll info
public void display() {
System.out.println(name + " is a funny troll");
}
}<file_sep>/WeaponBehavior.java
package csce247.assignments.strategy;
//<NAME> csce 247
//interface for the type of weapon and attacks
public interface WeaponBehavior {
public void attack();
}
<file_sep>/WeaponBow.java
package csce247.assignments.strategy;
//<NAME> csce 247
//attack for bow weapontype
public class WeaponBow implements WeaponBehavior {
public void attack() {
System.out.println("Draw and loose an arrow");
}
}
<file_sep>/King.java
package csce247.assignments.strategy;
//<NAME> csce 247
//Creates king character
public class King extends Character {
public King(String name) {
super(name);
//sets weapon to sword
weaponbehavior = new WeaponSword();
}
//displays king info
public void display() {
System.out.println(name + " is a noble king");
}
}<file_sep>/WeaponAxe.java
package csce247.assignments.strategy;
//<NAME> csce 247
//attack for axe weapontype
public class WeaponAxe implements WeaponBehavior {
public void attack() {
System.out.println("Swing an axe");
}
}
<file_sep>/Character.java
package csce247.assignments.strategy;
//<NAME> csce 247
//abstract class character
public abstract class Character {
protected String name;
WeaponBehavior weaponbehavior;
//constructor for character
public Character(String name) {
this.name = name;
}
//displays character
public abstract void display();
//character attacks
public void attack() {
weaponbehavior.attack();
}
//sets character's weapon
public void setWeaponBehavior(WeaponBehavior wb) {
this.weaponbehavior=wb;
}
}
<file_sep>/WeaponNone.java
package csce247.assignments.strategy;
//noah snell csce 247
//attacks with no weapon
public class WeaponNone implements WeaponBehavior {
public void attack() {
System.out.println("Oh no! I lost my weapon");
}
}
|
3d4f525c1cc7257b69e44e024c2ee213bd76e9c9
|
[
"Java"
] | 7 |
Java
|
hasnell/DesignPatterns
|
4e30586e50ae4a8314eb01ff26270de6c3faff0a
|
3889e19025534bc3d0f47d333ff434808565645e
|
refs/heads/master
|
<repo_name>haren619/swipejobs-test<file_sep>/README.md
## Prerequisites
Java 8
## How to Run
Build and run the application using maven wrapper.
./mvnw clean install
./mvnw spring-boot:run
Access below url in the browser.
http://localhost:8080/matcher/{workerId}
{workerId} -> worker id needs to be matched with jobs
** Refer ../target/site/jacoco/index.html for code coverage.
## Design
Matcher application will take a workerId and return three appropriate jobs with the highest score using the data retrieved from SwipeJob's workers and jobs apis.
In this solution application uses a basic Rule Engine design pattern. MatchingEngine calculates the matching score for each job against the given worker. MatchingService will then sort the jobs by their score and return 3 jobs with the highest score.
### Matching Rules
* Qualification Matcher
Worker should have all the certificates required by the job.
* Distance Matcher
Distance between the job and worker location should be less than the maximum distance preferred by the worker.
Job will be given a score based on the relative distance.
* Driving Licence Matcher
Worker should have driver licence if the job requests for it.
## Future Improvements
* Add new matching rule to map worker's availability with job start date.
* Improve distance matcher mechanism to provide more granular ratings.
* Rate jobs based on number of workers required so that worker will have a higher change.
* Rate jobs by billing rate.
<file_sep>/src/main/java/com/swipejobs/test/matcher/model/MatchingResult.java
package com.swipejobs.test.matcher.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class MatchingResult {
private boolean match;
private Integer score;
}
<file_sep>/src/test/java/com/swipejobs/test/matcher/engine/QualificationMatcherTest.java
package com.swipejobs.test.matcher.engine;
import com.swipejobs.test.matcher.model.Job;
import com.swipejobs.test.matcher.model.MatchingResult;
import com.swipejobs.test.matcher.model.Worker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
public class QualificationMatcherTest {
@Test
public void testQualificationsMatch() {
List<String> certificates = Arrays.asList("cert-1", "cert-2", "cert-3");
Job job = new Job();
job.setRequiredCertificates(certificates);
job.setJobId(1);
Worker worker = new Worker();
worker.setCertificates(certificates);
worker.setUserId(1);
QualificationMatcher matcher = new QualificationMatcher();
MatchingResult result = matcher.evaluate(worker, job);
Assertions.assertTrue(result.isMatch());
Assertions.assertEquals(1, result.getScore());
}
@Test
public void testQualificationsDoNotMatch() {
Job job = new Job();
job.setRequiredCertificates(Arrays.asList("cert-1", "cert-2", "cert-3"));
job.setJobId(1);
Worker worker = new Worker();
worker.setCertificates(Arrays.asList("cert-1", "cert-2"));
worker.setUserId(1);
QualificationMatcher matcher = new QualificationMatcher();
MatchingResult result = matcher.evaluate(worker, job);
Assertions.assertFalse(result.isMatch());
Assertions.assertEquals(0, result.getScore());
}
}
<file_sep>/src/main/java/com/swipejobs/test/matcher/service/WorkerService.java
package com.swipejobs.test.matcher.service;
import com.swipejobs.test.matcher.model.Worker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class WorkerService {
@Value("${swipejobs.workers.url}")
private String workersResourceUrl;
@Autowired
private RestTemplate restTemplate;
public Map<Integer, Worker> getWorkers() {
ResponseEntity<Worker[]> response
= restTemplate.getForEntity(workersResourceUrl, Worker[].class);
Worker[] jobArr = response.getBody();
//currently return a Map as api doesn't support query parameters
return Arrays.asList(jobArr)
.stream()
.collect(Collectors.toMap(Worker::getUserId, Function.identity()));
}
public void setWorkersResourceUrl(String workersResourceUrl) {
this.workersResourceUrl = workersResourceUrl;
}
}
<file_sep>/src/test/java/com/swipejobs/test/matcher/service/JobServiceTest.java
package com.swipejobs.test.matcher.service;
import com.swipejobs.test.matcher.model.Job;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import static org.mockito.Mockito.when;
@SpringBootTest
public class JobServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private JobService jobService;
@Test
public void testGetJobs() {
Job job = new Job();
job.setJobId(1);
Job[] jobArr = {job};
String url = "http://localhost:8080/test";
jobService.setJobsResourceUrl(url);
when(restTemplate.getForEntity(url, Job[].class))
.thenReturn(new ResponseEntity(jobArr, HttpStatus.OK));
Assertions.assertArrayEquals(jobArr, jobService.getJobs().toArray());
}
}
<file_sep>/src/main/java/com/swipejobs/test/matcher/web/MatcherController.java
package com.swipejobs.test.matcher.web;
import com.swipejobs.test.matcher.model.Job;
import com.swipejobs.test.matcher.service.MatchingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class MatcherController {
@Autowired
MatchingService matchingService;
@GetMapping("/matcher/{workerId}")
public List<Job> getMatchingJobs(@PathVariable Integer workerId){
return matchingService.getMatchingJobs(workerId);
}
}
<file_sep>/src/test/java/com/swipejobs/test/matcher/engine/MatchingEngineTest.java
package com.swipejobs.test.matcher.engine;
import com.swipejobs.test.matcher.model.Job;
import com.swipejobs.test.matcher.model.MatchingResult;
import com.swipejobs.test.matcher.model.Worker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Arrays;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@SpringBootTest
public class MatchingEngineTest {
private Job job;
private Worker worker;
@Mock
private DistanceMatcher distanceMatcher;
@Mock
private DrivingLicenceMatcher drivingLicenceMatcher;
@Mock
private QualificationMatcher qualificationMatcher;
@InjectMocks
private MatchingEngine matchingEngine;
@BeforeEach
public void setup() {
matchingEngine.setMatchers(Arrays.asList(distanceMatcher, drivingLicenceMatcher, qualificationMatcher));
job = new Job();
job.setJobId(1);
worker = new Worker();
worker.setUserId(1);
}
@Test
public void testNoneMatch() {
when(distanceMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(false, 0));
when(drivingLicenceMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(false, 0));
when(qualificationMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(false, 0));
Optional<Integer> result = matchingEngine.getMatchingScore(worker, job);
Assertions.assertEquals(Optional.empty(), result);
}
@Test
public void testAllMatch() {
when(distanceMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(true, 1));
when(drivingLicenceMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(true, 2));
when(qualificationMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(true, 4));
Optional<Integer> result = matchingEngine.getMatchingScore(worker, job);
Assertions.assertEquals(Optional.of(7), result);
}
@Test
public void testAnyNoneMatch() {
when(distanceMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(false, 0));
when(drivingLicenceMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(true, 2));
when(qualificationMatcher.evaluate(any(), any())).thenReturn(new MatchingResult(true, 3));
Optional<Integer> result = matchingEngine.getMatchingScore(worker, job);
Assertions.assertEquals(Optional.empty(), result);
}
}
|
590e77dce8d29310293c47aabf9cd8448a8af6f6
|
[
"Java",
"Markdown"
] | 7 |
Java
|
haren619/swipejobs-test
|
a85ec3fbe1ca3781da4eb13b794475711f20ed9a
|
499b6212d32058c8f9c5a42f6868993fb4e32334
|
refs/heads/master
|
<file_sep># firstbook
* [Introduction](README.md)
* [ARM Cortex-M 处理器简介](chapter1/README.md)
* [什么是ARM Cortex-M处理器](chapter1/section1.md)
* [Cortex-M处理器家族](chapter1/section1.1.md)
* [处理器和微控制器的区别](chapter1/section1.2.md)
* [ARM Cortex-M处理器的优势](chapter1/section2.md)
* [低功耗](chapter2/section2.1.md)
* [代码密度](chapter2/section2.2.md)
|
ff78a68dc3eafb67360ab3c23dbc35cdd1891fa1
|
[
"Markdown"
] | 1 |
Markdown
|
oneWalker/firstbook
|
8a29c8eee466bc580a60452caa0d47f61e46b14e
|
a8acd0d50144422cb43dd095802223c95c47af9f
|
refs/heads/master
|
<repo_name>cingL/page<file_sep>/script.js
$(document).on('ready', function() {
var bgcolor = ['red', 'yellow', 'blue']
var text = ['red', 'yellow', 'blue']
$('.image').slick({
dots: true,
infinite: true,
speed: 500,
fade: true,
cssEase: 'linear',
arrows: false
});
var list = $('button')
for (var i = list.length - 1; i >= 0; i--) {
console.log(list[i])
$(list[i]).css('border', '1px solid ' + bgcolor[i])
$(list[i]).css('border-radius', "50%")
}
$('.image').append("<div class='title'>red</div>")
$('.image').on('swipe', function(event, slick, direction) {
// console.log(event);
$('body').css('background-color', bgcolor[slick.currentSlide])
$('.title').text(text[slick.currentSlide])
console.log($('button')[slick.currentSlide]);
var list = $('button')
for (var i = list.length - 1; i >= 0; i--) {
console.log(list[i])
$(list[i]).css('border-color', bgcolor[i])
}
});
});
|
188491b095239c3543af0e556224a89c4db1e749
|
[
"JavaScript"
] | 1 |
JavaScript
|
cingL/page
|
f4c0a75a1e5bba818d49a4d8b226682648e2c527
|
777d44d59e68cc7e20c7db6062cb9629715f10cf
|
refs/heads/main
|
<repo_name>luizgualmeida/Trust-in-science-social-consensus-and-vaccine-confidence<file_sep>/NHB - Trust in science, social consensus and vaccine confidence (model code).R
#NATURE HUMAN BEHAVIOR - Trust in science, social consensus, and vaccine confidence
# Loading packages and data -------------------------------------------
library(effects)
library(tidyverse)
library(haven)
library(readxl)
library(ltm)
library(lme4)
library(rstan)
library(brms)
library(ggrepel)
library(RColorBrewer)
library(stargazer)
library(tidybayes)
library(mice)
# Reading in Raw data -----------------------------------------------------
setwd([insert file location here])
wgm.2018.original <- read_dta("Wellcome_Trust_February_originalfileSTATA.dta")
#WORLD BANK INDICATOR DATA
# https://databank.worldbank.org/home.aspx
WBI.raw <- read_csv("WBI_v1.csv") %>%
drop_na(`Country Code`) %>%
subset(select = (-`Series Code`)) %>%
na_if("..")
gini.raw <- read_excel("inequality_index_gini.xlsx")
# https://datacatalog.worldbank.org/dataset/human-capital-index
HCI.raw <- read_csv("HCIData.csv") %>%
subset(select = (-`Indicator Code`))
# Restructuring all country-level data ------------------------------------
#Identifying appropriate WBI data
WBI.reduced <- subset(WBI.raw, `Series Name` == "Population, total" |
`Series Name` == "Adjusted net national income per capita (current US$)" |
`Series Name` == "GDP per capita (current US$)" |
`Series Name` == "Intentional homicides (per 100,000 people)" |
`Series Name` == "Poverty headcount ratio at $1.90 a day (2011 PPP) (% of population)" |
`Series Name` == "Poverty headcount ratio at $3.20 a day (2011 PPP) (% of population)" |
`Series Name` =="CPIA transparency, accountability, and corruption in the public sector rating (1=low to 6=high)") %>%
rename(`2009` = `2009 [YR2009]`,
`2010` = `2010 [YR2010]`,
`2011` = `2011 [YR2011]`,
`2012` = `2012 [YR2012]`,
`2013` = `2013 [YR2013]`,
`2014` = `2014 [YR2014]`,
`2015` = `2015 [YR2015]`,
`2016` = `2016 [YR2016]`,
`2017` = `2017 [YR2017]`,
`2018` = `2018 [YR2018]`) %>%
pivot_longer(c(`2009`:`2018`), names_to = "year", values_to = "total") %>%
group_by(`Country Name`, `Series Name`)%>%
fill(total) %>%
ungroup()%>%
filter(year==2018) %>%
group_by(`Country Name`) %>%
pivot_wider(names_from = `Series Name`, values_from = `total`)
WBI.reduced$population.total <- as.numeric(WBI.reduced$`Population, total`)
WBI.reduced$income.per.capita <- as.numeric(WBI.reduced$`Adjusted net national income per capita (current US$)`)
WBI.reduced$gdp.per.capita <- as.numeric(WBI.reduced$`GDP per capita (current US$)`)
WBI.reduced$homicides <- as.numeric(WBI.reduced$`Intentional homicides (per 100,000 people)`)
WBI.reduced$poverty.190 <- as.numeric(WBI.reduced$`Poverty headcount ratio at $1.90 a day (2011 PPP) (% of population)`)
WBI.reduced$poverty.320 <- as.numeric(WBI.reduced$`Poverty headcount ratio at $3.20 a day (2011 PPP) (% of population)`)
WBI.reduced$CPIA <- as.numeric(WBI.reduced$`CPIA transparency, accountability, and corruption in the public sector rating (1=low to 6=high)`)
WBI <- WBI.reduced %>%
subset(select = c(`Country Name`, population.total, income.per.capita, gdp.per.capita, homicides, poverty.190, poverty.320, CPIA))
#Identifying appropriate HCI data
HCI.reduced <- subset(HCI.raw, `Indicator Name` == "Harmonized Test Scores" |
`Indicator Name` == "Human Capital Index (HCI) (scale 0-1)") %>%
group_by(`Country Name`) %>%
pivot_wider(names_from = `Indicator Name`, values_from = `2017`) %>%
rename(`HLO` = `Harmonized Test Scores`,
`HCI` = `Human Capital Index (HCI) (scale 0-1)`)
HLO <- HCI.reduced %>%
subset(select = c(`Country Name`, HLO, HCI))
#Identifying appropriate gini data
gini <- gini.raw %>%
pivot_longer(c(`1967`:`2018`), names_to = "year", values_to = "gini")%>%
group_by(country)%>%
fill(gini)%>%
ungroup()%>%
filter(year==2018) %>%
subset(select = (-year))
rm(WBI.raw, WBI.reduced, HCI.raw, HCI.reduced, gini.raw)
# Data wrangling ----------------------------------------------------------
###Linking country data to WGM
wgm.2018.original$country <- as_factor(wgm.2018.original$countrynew)
wgm.2018.original$country <- as.character(wgm.2018.original$country)
table(wgm.2018.original$country)
#WGM - compare against map_data
country.code <- wgm.2018.original %>%
group_by(country) %>%
summarise(country = first(country)) %>%
subset(select = (country))
WorldData <- map_data('world')
WorldData %>% filter(region != "Antarctica") -> WorldData
WorldData <- fortify(WorldData)
WorldData$region[WorldData$subregion=="Hong Kong"] <- "Hong Kong" #Adding in HK
WorldData$region[WorldData$subregion=="Macau"] <- "Macau" #Adding in Macau
data <- as.data.frame(WorldData$region)%>%
group_by(`WorldData$region`) %>%
summarise(`Country` = first(`WorldData$region`))
missing.countries <- country.code %>%
anti_join(data, by = c("country" = "WorldData$region"))
table(WorldData$region)
table(missing.countries$country)
#WBI - compare against revised WGM
missing.countries <- country.code %>%
anti_join(WBI, by = c("country" = "Country Name"))
table(missing.countries$country) #Taiwan not available
table(WBI$`Country Name`) #Taiwan not available
WBI$`Country Name`[WBI$`Country Name`=="Egypt, Arab Rep."] <- "Egypt"
WBI$`Country Name`[WBI$`Country Name`=="Gambia, The"] <- "Gambia"
WBI$`Country Name`[WBI$`Country Name`=="Iran, Islamic Rep."] <- "Iran"
WBI$`Country Name`[WBI$`Country Name`=="Cote d'Ivoire"] <- "Ivory Coast"
WBI$`Country Name`[WBI$`Country Name`=="Kyrgyz Republic"] <- "Kyrgyzstan"
WBI$`Country Name`[WBI$`Country Name`=="Lao PDR"] <- "Laos"
WBI$`Country Name`[WBI$`Country Name`=="Macedonia, FYR"] <- "Macedonia"
WBI$`Country Name`[WBI$`Country Name`=="West Bank and Gaza"] <- "Palestine"
WBI$`Country Name`[WBI$`Country Name`=="Russian Federation"] <- "Russia"
WBI$`Country Name`[WBI$`Country Name`=="Congo, Rep."] <- "Republic of Congo"
WBI$`Country Name`[WBI$`Country Name`=="Slovak Republic"] <- "Slovakia"
WBI$`Country Name`[WBI$`Country Name`=="Korea, Rep."] <- "South Korea"
WBI$`Country Name`[WBI$`Country Name`=="Eswatini"] <- "Swaziland"
WBI$`Country Name`[WBI$`Country Name`=="United Kingdom"] <- "UK"
WBI$`Country Name`[WBI$`Country Name`=="United States"] <- "USA"
WBI$`Country Name`[WBI$`Country Name`=="Venezuela, RB"] <- "Venezuela"
WBI$`Country Name`[WBI$`Country Name`=="Yemen, Rep."] <- "Yemen"
#HLO - compare against revised WGM
missing.countries <- country.code %>%
anti_join(HLO, by = c("country" = "Country Name"))
table(missing.countries$country) #Belarus, Bolivia, Libya, Taiwan, Turkmenistan, Uzbekistan, Venezuela not available
table(HLO$`Country Name`)
HLO$`Country Name`[HLO$`Country Name`=="Egypt, Arab Rep."] <- "Egypt"
HLO$`Country Name`[HLO$`Country Name`=="Gambia, The"] <- "Gambia"
HLO$`Country Name`[HLO$`Country Name`=="Iran, Islamic Rep."] <- "Iran"
HLO$`Country Name`[HLO$`Country Name`=="Cote d'Ivoire"] <- "Ivory Coast"
HLO$`Country Name`[HLO$`Country Name`=="Kyrgyz Republic"] <- "Kyrgyzstan"
HLO$`Country Name`[HLO$`Country Name`=="Lao PDR"] <- "Laos"
HLO$`Country Name`[HLO$`Country Name`=="Macedonia, FYR"] <- "Macedonia"
HLO$`Country Name`[HLO$`Country Name`=="West Bank and Gaza"] <- "Palestine"
HLO$`Country Name`[HLO$`Country Name`=="Congo, Rep."] <- "Republic of Congo"
HLO$`Country Name`[HLO$`Country Name`=="Russian Federation"] <- "Russia"
HLO$`Country Name`[HLO$`Country Name`=="Slovak Republic"] <- "Slovakia"
HLO$`Country Name`[HLO$`Country Name`=="Korea, Rep."] <- "South Korea"
HLO$`Country Name`[HLO$`Country Name`=="Eswatini"] <- "Swaziland"
HLO$`Country Name`[HLO$`Country Name`=="United Kingdom"] <- "UK"
HLO$`Country Name`[HLO$`Country Name`=="United States"] <- "USA"
HLO$`Country Name`[HLO$`Country Name`=="Yemen, Rep."] <- "Yemen"
#Gini - compare against revised WGM
missing.countries <- country.code %>%
anti_join(gini, by = "country")
table(missing.countries$country) ##Afghanistan, Cambodia, Kosovo, Kuwait, Libya, NewZeland, Saudo Arabia, Singapore, Taiwan not available
table(gini$country)
gini$country[gini$country=="Cote d'Ivoire"] <- "Ivory Coast"
gini$country[gini$country=="Kyrgyz Republic"] <- "Kyrgyzstan"
gini$country[gini$country=="Lao"] <- "Laos"
gini$country[gini$country=="North Macedonia"] <- "Macedonia" #Wrong in NHB paper??
gini$country[gini$country=="Congo, Rep."] <- "Republic of Congo"
gini$country[gini$country=="Slovak Republic"] <- "Slovakia"
gini$country[gini$country=="United Kingdom"] <- "UK"
gini$country[gini$country=="United States"] <- "USA"
#Coding individual level data
#Gender
attributes(wgm.2018.original$WP1219)
table(wgm.2018.original$WP1219)
wgm.2018.original$male <- ifelse(wgm.2018.original$WP1219==1, 1, 0)
table(wgm.2018.original$male)
#Age
table(wgm.2018.original$WP1220)
wellcome.country$age_c <- wellcome.country$WP1220 - mean(wellcome.country$WP1220, na.rm = TRUE)
#Education
attributes(wgm.2018.original$WP3117)
table(wgm.2018.original$WP3117)
wgm.2018.original$ed_mid <- ifelse(wgm.2018.original$WP3117==2, 1, 0)
wgm.2018.original$ed_mid[wgm.2018.original$WP3117==4 | wgm.2018.original$WP3117==5] <- NA
wgm.2018.original$ed_high <- ifelse(wgm.2018.original$WP3117==3, 1, 0)
wgm.2018.original$ed_high[wgm.2018.original$WP3117==4 | wgm.2018.original$WP3117==5] <- NA
table(wgm.2018.original$ed_mid)
table(wgm.2018.original$ed_high)
#Income
wgm.2018.original$lg_inc2 <- log1p(wgm.2018.original$income_2)
summary(wgm.2018.original$lg_inc2)
wgm.2018.original$lg_inc2[wgm.2018.original$lg_inc2==0] <- NA
#Vaccine support
wgm.2018.original %>%
subset(., select = c(WP20010, WP20011, WP20012, WP20013, WP20014, WP20015, WP20016, WP20017, WP20018)) %>%
sapply(attr,"label")
table(wgm.2018.original$WP20010)
wgm.2018.original$vac_child_bin2 <- ifelse(wgm.2018.original$WP20010==1, 1, 0)
wgm.2018.original$vac_child_bin2[wgm.2018.original$WP20010==98 | wgm.2018.original$WP20010==99] <- NA
table(wgm.2018.original$vac_child_bin2)
table(wgm.2018.original$WP20013)
wgm.2018.original$vac_safe_bin2 <- ifelse(wgm.2018.original$WP20013==1, 1, 0)
wgm.2018.original$vac_safe_bin2[wgm.2018.original$WP20013==98 | wgm.2018.original$WP20013==99] <- NA
table(wgm.2018.original$vac_safe_bin2)
table(wgm.2018.original$WP20016)
wgm.2018.original$vac_effect_bin2 <- ifelse(wgm.2018.original$WP20016==1, 1, 0)
wgm.2018.original$vac_effect_bin2[wgm.2018.original$WP20016==98 | wgm.2018.original$WP20016==99] <- NA
table(wgm.2018.original$vac_effect_bin2)
wgm.2018.original$vaccine <- wgm.2018.original$vac_child_bin2 + wgm.2018.original$vac_safe_bin2 + wgm.2018.original$vac_effect_bin2
table(wgm.2018.original$vaccine)
wgm.2018.original$vaccine_bin2 <- ifelse(wgm.2018.original$vaccine==3, 1, 0)
table(wgm.2018.original$vaccine_bin2)
# Measuring trust in science - IRT models ----------------------------------------------
wgm.2018.original %>%
subset(., select = c(WP19991, WP19993, WP19996, WP19997, WP19998, WP19999, WP20000, WP20001, WP20007, WP20008)) %>%
sapply(attr,"label")
#Full 7-item scale
wgm.2018.original %>%
subset(., select = c(WP19991, WP19996, WP19997, WP19998, WP19999, WP20000, WP20001)) %>%
sapply(attr,"label")
table(wgm.2018.original$WP19991)
table(wgm.2018.original$WP19996)
table(wgm.2018.original$WP19997)
table(wgm.2018.original$WP19998)
table(wgm.2018.original$WP19999)
table(wgm.2018.original$WP20000)
table(wgm.2018.original$WP20001)
wgm.2018.original$WP19991[wgm.2018.original$WP19991 ==98 | wgm.2018.original$WP19991==99] <- NA
wgm.2018.original$WP19996[wgm.2018.original$WP19996 ==98 | wgm.2018.original$WP19996==99] <- NA
wgm.2018.original$WP19997[wgm.2018.original$WP19997 ==98 | wgm.2018.original$WP19997==99] <- NA
wgm.2018.original$WP19998[wgm.2018.original$WP19998 ==98 | wgm.2018.original$WP19998==99] <- NA
wgm.2018.original$WP19999[wgm.2018.original$WP19999 ==98 | wgm.2018.original$WP19999==99] <- NA
wgm.2018.original$WP20000[wgm.2018.original$WP20000 ==98 | wgm.2018.original$WP20000==99] <- NA
wgm.2018.original$WP20001[wgm.2018.original$WP20001 ==98 | wgm.2018.original$WP20001==99] <- NA
wgm.2018.original <-wgm.2018.original %>%
mutate_at(vars(WP19991, WP19996, WP19997, WP19998, WP19999, WP20000, WP20001),
list("2" = ~ 5 - .))
wgm.2018.irt <- subset(wgm.2018.original, select = c(WP19991_2, WP19996_2, WP19997_2, WP19998_2, WP19999_2, WP20000_2, WP20001_2))
irt.1 <- grm(wgm.2018.irt) #graded response model
coef(irt.1) #Invert values for reporting to match Stata
summary(irt.1)
science.trust <- factor.scores(irt.1, method = "EAP", resp.patterns = wgm.2018.irt)$score.dat #These match stata , latent option
science.trust$trust_science_full <- science.trust$z1*(-1) #Invert scale so higher score means more trust
science.trust$trust_science_full[is.na(science.trust$WP19991_2) & is.na(science.trust$WP19996_2) & is.na(science.trust$WP19997_2) & is.na(science.trust$WP19998_2) & is.na(science.trust$WP19999_2) & is.na(science.trust$WP20000_2) & is.na(science.trust$WP20001_2)] <- NA
science.trust <- science.trust %>%
rowid_to_column("ID") %>%
subset(select = c(ID, trust_science_full))
wgm.2018.original <- wgm.2018.original %>%
rowid_to_column("ID") %>%
left_join(science.trust, by = "ID")
#Medical professionals
wgm.2018.original %>%
subset(., select = c(WP19993, WP20008)) %>%
sapply(attr,"label")
table(wgm.2018.original$WP19993)
table(wgm.2018.original$WP20008)
wgm.2018.original$WP19993[wgm.2018.original$WP19993 ==98 | wgm.2018.original$WP19993==99] <- NA
wgm.2018.original$WP20008[wgm.2018.original$WP20008 ==98 | wgm.2018.original$WP20008==99] <- NA
wgm.2018.original <-wgm.2018.original %>%
mutate_at(vars(WP19993, WP20008),
list("2" = ~ 5 - .))
wgm.2018.irt2 <- subset(wgm.2018.original, select = c(WP19993_2, WP20008_2))
irt.2 <- grm(wgm.2018.irt2) #graded response model
coef(irt.2) #Values matched to stata
summary(irt.2)
science.trust2 <- factor.scores(irt.2, method = "EAP", resp.patterns = wgm.2018.irt2)$score.dat #These match stata , latent option
science.trust2$trust_med_advice <- science.trust2$z1
science.trust2$trust_med_advice[is.na(science.trust2$WP19991_2) & is.na(science.trust2$WP19996_2)] <- NA
science.trust2 <- science.trust2 %>%
rowid_to_column("ID") %>%
subset(select = c(ID, trust_med_advice))
wgm.2018.original <- wgm.2018.original %>%
left_join(science.trust2, by = "ID")
# Merge all country data and tidy -----------------------------------------
wellcome.country <- wgm.2018.original %>%
left_join(WBI, by = c("country" = "Country Name")) %>%
left_join(HLO, by = c("country" = "Country Name")) %>%
left_join(gini, by = "country")
rm(country.code, data, gini, HLO, missing.countries, WBI, WorldData, science.trust, science.trust2, wgm.2018.irt, wgm.2018.irt2)
# Evaluating the distribtion of trust in scientists - Using full trust scale [7-items - 11c, 12, 13, 14a, 14b, 15a, 15b] ------------------------
ggplot(data = wellcome.country, mapping = aes(x = trust_science_full)) +
geom_histogram(bins = 30, color = "black", fill= "white", na.rm=TRUE)
#Separately by country
ggplot(data = wellcome.country, mapping = aes(x = trust_science_full)) +
geom_histogram(bins = 30, color = "black", fill= "white", na.rm=TRUE) +
facet_wrap(facets = wellcome.country$WP5)
# TABLE 1: Estimating location-scale model - Using full trust scale [7-items - 11c, 12, 13, 14a, 14b, 15a, 15b]-----------------------------------------
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
#Full model
trust7_full.gm <- brm(bf(trust_science_full ~ 1 + scale(gdp.per.capita) + scale(HLO) + scale(gini) + scale(male, scale=FALSE) + I(age_c/10) + scale(ed_mid, scale=FALSE) + scale(ed_high, scale=FALSE) + scale(lg_inc2, center=TRUE) + (1 |s| countrynew), sigma ~ 1 + scale(gdp.per.capita) + scale(HLO) + scale(gini) + scale(male, scale=FALSE) + I(age_c/10) + scale(ed_mid, scale=FALSE) + scale(ed_high, scale=FALSE) + scale(lg_inc2, center=TRUE) + (1 |s| countrynew)),
data = wellcome.country,
family = gaussian(),
chains = 4,
iter = 20000)
print(summary(trust7_full.gm), digits = 3)
mcmc_plot(trust7_full.gm, type = "trace")
#Extracting and saving location-scale residuals for subsequent analyses
effects.trust7_full.gm<-ranef(trust7_full.gm)
effects.trust7_full.gm<-as.data.frame(effects.trust7_full.gm)
effects.trust7_full.gm$Country <- rownames(effects.trust7_full.gm)
effects.trust7_full.gm$trust_u0 <- effects.trust7_full.gm$countrynew.Estimate.Intercept
effects.trust7_full.gm$vac_m2.5 <- effects.trust7_full.gm$countrynew.Q2.5.Intercept
effects.trust7_full.gm$vac_m97.5 <- effects.trust7_full.gm$countrynew.Q97.5.Intercept
effects.trust7_full.gm$trust_u1 <- effects.trust7_full.gm$countrynew.Estimate.sigma_Intercept
effects.trust7_full.gm$vac_sd2.5 <- effects.trust7_full.gm$countrynew.Q2.5.sigma_Intercept
effects.trust7_full.gm$vac_sd97.5 <- effects.trust7_full.gm$countrynew.Q97.5.sigma_Intercept
effects.trust7_full.gm <- effects.trust7_full.gm %>%
subset(select = c(Country, trust_u0, trust_u1))
wellcome.effects <- merge(wellcome.country, effects.trust7_full.gm, by.x = "country", by.y = "Country", all.x=TRUE, all.y=TRUE)
#Plotting the residuals - u0 and u1 from location-scale model - to check assumptions
ggplot(data = effects.trust7_full.gm, mapping = aes(x = trust_u0)) +
geom_histogram(bins = 30, color = "black", fill= "white", na.rm=TRUE)
ggplot(data = effects.trust7_full.gm, mapping = aes(x = trust_u1)) +
geom_histogram(bins = 30, color = "black", fill= "white", na.rm=TRUE)
#Assessing the correlation of the location and scale residuals
ggplot(data=effects.trust7_full.gm, mapping = aes(x = trust_u0, y = trust_u1)) +
geom_point()
cor.test(effects.trust7_full.gm$trust_u0, effects.trust7_full.gm$trust_u1)
#Comparison against raw mean and SD
wellcome.country.mean <- wellcome.country %>%
group_by(countrynew) %>%
summarise(
trust_mean = mean(trust_science_full, na.rm=TRUE),
trust_sd = sd(trust_science_full, na.rm=TRUE)
)
ggplot(data=wellcome.country.mean, mapping = aes(x = trust_mean, y = trust_sd)) +
geom_point()
cor.test(wellcome.country.mean$trust_mean, wellcome.country.mean$trust_sd)
#FIGURE 1: Plotted using full trust scale [7-items - 11c, 12, 13, 14a, 14b, 15a, 15b]-----------------------------------------
#Define plot
palette <- brewer.pal("Greys", n=9)
color.background = palette[1]
color.grid.major = palette[5]
color.axis.text = palette[6]
color.axis.title = palette[7]
color.title = palette[9]
#Extract estimated mean and SD for each country
effectsSD.trust_full.gm<-coef(trust7_full.gm)
effectsSD.trust_full.gm<-as.data.frame(effectsSD.trust_full.gm)
effectsSD.trust_full.gm$Country <- rownames(effectsSD.trust_full.gm)
effectsSD.trust_full.gm$trust_mean <- effectsSD.trust_full.gm$countrynew.Estimate.Intercept
effectsSD.trust_full.gm$vac_m2.5 <- effectsSD.trust_full.gm$countrynew.Q2.5.Intercept
effectsSD.trust_full.gm$vac_m97.5 <- effectsSD.trust_full.gm$countrynew.Q97.5.Intercept
effectsSD.trust_full.gm$trust_sd <- exp(effectsSD.trust_full.gm$countrynew.Estimate.sigma_Intercept)
effectsSD.trust_full.gm$vac_sd2.5 <- exp(effectsSD.trust_full.gm$countrynew.Q2.5.sigma_Intercept)
effectsSD.trust_full.gm$vac_sd97.5 <- exp(effectsSD.trust_full.gm$countrynew.Q97.5.sigma_Intercept)
effectsSD.trust_full.gm <- effectsSD.trust_full.gm %>%
subset(select= c(Country, trust_mean, trust_sd, vac_sd2.5, vac_sd97.5))
effectsSD.trust_full.gm <- effectsSD.trust_full.gm %>%
mutate(ranking_m = rank(trust_mean, ties.method = 'first'),
ranking_sd = rank(trust_sd, ties.method = 'first'),
mean_sd = mean(trust_sd))
ggplot()+
geom_pointrange(data=effectsSD.trust_full.gm,mapping=aes(x=ranking_sd, y=trust_sd, ymin=vac_sd2.5,ymax=vac_sd97.5), position="identity", width=0.5, size=.1, color="black")+
theme_bw() +
# Set the entire chart region to a light gray color
theme(panel.background=element_rect(fill=color.background, color=color.background)) +
theme(plot.background=element_rect(fill=color.background, color=color.background)) +
theme(axis.ticks=element_blank()) +
# Set title and axis labels, and format these and tick marks
theme(plot.title=element_text(face="bold",hjust=-.08,vjust=2,colour="#3C3C3C",size=20))+
xlab("Countries (ranked)") +
ylab("Estimated SD for trust in science") +
# Big bold line at y=0
geom_hline(yintercept=effectsSD.trust_full.gm$mean_sd, size=.5, alpha=0.7,colour="#EF3B2C", linetype="twodash") +
geom_text_repel(aes(x=effectsSD.trust_full.gm$ranking_sd, y=effectsSD.trust_full.gm$trust_sd, label=ifelse(effectsSD.trust_full.gm$ranking_sd<10,as.character(effectsSD.trust_full.gm$Country),'')),
segment.alpha = .1, nudge_y = -4, size=2) +
geom_text_repel(aes(x=effectsSD.trust_full.gm$ranking_sd, y=effectsSD.trust_full.gm$trust_sd, label=ifelse(effectsSD.trust_full.gm$ranking_sd>115,as.character(effectsSD.trust_full.gm$Country),'')),
segment.alpha = .1, nudge_y = 4, size=2)
# TABLE 2: Estimating multilevel models - Using full trust scale [7-items - 11c, 12, 13, 14a, 14b, 15a, 15b] ----------------------------------------
wellcome.effects <- merge(wellcome.country, effects.trust7_full.gm, by.x = "country", by.y = "Country", all.x=TRUE, all.y=TRUE)
#Binary model (coding 4/5 as positive)
###Model 1
bin.1 <- glmer(vaccine_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
summary(bin.1)
###Model 2
bin.2 <- glmer(vaccine_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
summary(bin.2)
##Vaccine sub-scales
bin.1.child <- glmer(vac_child_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
bin.2.child <- glmer(vac_child_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
bin.1.safe <- glmer(vac_safe_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
bin.2.safe <- glmer(vac_safe_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
bin.1.effect <- glmer(vac_effect_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
bin.2.effect <- glmer(vac_effect_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects)
stargazer(bin.1.child, bin.2.child, bin.1.safe, bin.2.safe, bin.1.effect, bin.2.effect, type="text")
summary(bin.1.child)
summary(bin.2.child)
summary(bin.1.safe)
summary(bin.2.safe)
summary(bin.1.effect)
summary(bin.2.effect)
# FIGURE 2: Plotting interaction effects from model 2-------------------------------------------------------
#Panel 1: Country-level trust in science and vaccine confidence
#Identifying cut points
effects.trust7_full.gm$trust_u1_5 <-ntile(effects.trust7_full.gm$trust_u1, 5)
effects.trust7_full.gm %>%
group_by(trust_u1_5) %>%
summarise(
trust_var = mean(trust_u1, na.rm=TRUE)
)
eff7.country <- effect("trust_u0*trust_u1", bin.2, kr=TRUE,
xlevels=list(trust_u1 = c(-.15, -.06, 0, .06, .16)),
se=TRUE, confidence.level=.95, typical=mean)
trust.labs <- c(`-0.15` = "High trust consensus (Q1)", `-0.06` = "Q2", `0` = "Moderate trust consensus (Q3)", `0.06` = "Q4", `0.16` = "Weak trust consensus (Q5)")
data.country <- as.data.frame(eff7.country)
ggplot(data=data.country, aes(x=trust_u0, y = fit)) +
geom_smooth(method = "glm") +
geom_line(aes(y = lower,
group=factor(trust_u1)), linetype =3) +
geom_line(aes(y = upper,
group=factor(trust_u1)), linetype =3) +
geom_ribbon(aes(ymin = lower, ymax=upper), alpha=.08) +
xlab("Average trust in science") +
ylab("Marginal effects on vaccine confidence") +
theme_light(base_size = 16) +
scale_y_continuous(trans = "probit") +
facet_wrap(~ trust_u1,labeller=labeller(trust_u1=trust.labs), nrow=1)
#Panel 2: Individual-level trust in science and vaccine support
eff.individual <- effect("trust_science_full*trust_u1", bin.2, kr=TRUE,
xlevels=list(trust_u1 = c(-.15, -.06, 0, .06, .16)),
se=TRUE, confidence.level=.95, typical=mean)
data.individual <- as.data.frame(eff.individual)
ggplot(data=data.individual, aes(x=trust_science_full, y = fit)) +
geom_smooth(method="glm") +
geom_line(aes(y = lower,
group=factor(trust_u1)), linetype =3) +
geom_line(aes(y = upper,
group=factor(trust_u1)), linetype =3) +
geom_ribbon(aes(ymin = lower, ymax=upper), alpha=.08) +
xlab("Individual trust in science") +
ylab("Marginal effects on vaccine confidence") +
theme_light(base_size = 16) +
scale_y_continuous(trans = "probit") +
facet_wrap(~ trust_u1,labeller=labeller(trust_u1=trust.labs), nrow=1)
# SUPLEMENTARY MATERIALS ------------------------------------------
#SUPPLEMENTARY TABLES
#TABLE S1: IRT model results (invert to match Stata)
coef(irt.1) #Invert values for reporting to match Stata
summary(irt.1)
#TABLE S2: Location-scale model parameter estimates for trust in science across countries (imputed)
wellcome.country.imp <- wellcome.country %>%
subset(select = c(countrynew, male, trust_science_full, age_c, ed_mid, ed_high, lg_inc2, gdp.per.capita, gini, HLO))
imputed_Data <- mice(wellcome.country.imp, m=5, maxit = 50, method = 'pmm')
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
trust_imp.gm <- brm_multiple(bf(trust_science_full ~ 1 + scale(gdp.per.capita) + scale(HLO) + scale(gini) + scale(male, scale=FALSE) + I(age_c/10) + scale(ed_mid, scale=FALSE) + scale(ed_high, scale=FALSE) + scale(lg_inc2, center=TRUE) + (1 |s| countrynew), sigma ~ 1 + scale(gdp.per.capita) + scale(HLO) + scale(gini) + scale(male, scale=FALSE) + I(age_c/10) + scale(ed_mid, scale=FALSE) + scale(ed_high, scale=FALSE) + scale(lg_inc2, center=TRUE) + (1 |s| countrynew)),
data = imputed_Data,
family = gaussian(),
chains = 4,
iter = 20000)
print(summary(trust_imp.gm), digits = 3)
#TABLE S3: Interaction model for social norms, trust in science and vaccine confidence (imputed)
effects.imputed<-ranef(trust_imp.gm)
effects.imputed<-as.data.frame(effects.imputed)
effects.imputed$Country <- rownames(effects.imputed)
effects.imputed$trust_u0 <- effects.imputed$countrynew.Estimate.Intercept
effects.imputed$vac_m2.5 <- effects.imputed$countrynew.Q2.5.Intercept
effects.imputed$vac_m97.5 <- effects.imputed$countrynew.Q97.5.Intercept
effects.imputed$trust_u1 <- effects.imputed$countrynew.Estimate.sigma_Intercept
effects.imputed$vac_sd2.5 <- effects.imputed$countrynew.Q2.5.sigma_Intercept
effects.imputed$vac_sd97.5 <- effects.imputed$countrynew.Q97.5.sigma_Intercept
effects.imputed <- effects.imputed %>%
subset(select = c(Country, trust_u0, trust_u1))
wellcome.effects.imputed <-merge(wellcome.country, effects.imputed, by.x = "country", by.y = "Country", all.x=TRUE, all.y=TRUE)
bin.1.imp <- glmer(vaccine_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
summary(bin.1.imp)
bin.2.imp <- glmer(vaccine_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
summary(bin.2.imp)
bin.1.child.imp <- glmer(vac_child_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
bin.2.child.imp <- glmer(vac_child_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
bin.1.safe.imp <- glmer(vac_safe_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
bin.2.safe.imp <- glmer(vac_safe_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
bin.1.effect.imp <- glmer(vac_effect_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
bin.2.effect.imp <- glmer(vac_effect_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.imputed)
summary(bin.1.child.imp)
summary(bin.2.child.imp)
summary(bin.1.safe.imp)
summary(bin.2.safe.imp)
summary(bin.1.effect.imp)
summary(bin.2.effect.imp)
#TABLE S4: Location-scale model parameter estimates for trust in science (medical professionals) - 11e, 22
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
trustmed_full.gm <- brm(bf(trust_med_advice ~ 1 + scale(gdp.per.capita) + scale(HLO) + scale(gini) + scale(male, scale=FALSE) + I(age_c/10) + scale(ed_mid, scale=FALSE) + scale(ed_high, scale=FALSE) + scale(lg_inc2, center=TRUE) + (1 |s| countrynew), sigma ~ 1 + scale(gdp.per.capita) + scale(HLO) + scale(gini) + scale(male, scale=FALSE) + I(age_c/10) + scale(ed_mid, scale=FALSE) + scale(ed_high, scale=FALSE) + scale(lg_inc2, center=TRUE) + (1 |s| countrynew)),
data = wellcome.country,
family = gaussian(),
chains = 4,
iter = 20000)
print(summary(trustmed_full.gm), digits = 3)
#TABLE S5: Interaction model for social norms, trust in science (medical professionals) and vaccine confidence
effects.trustmed_full.gm<-ranef(trustmed_full.gm)
effects.trustmed_full.gm<-as.data.frame(effects.trustmed_full.gm)
effects.trustmed_full.gm$Country <- rownames(effects.trustmed_full.gm)
effects.trustmed_full.gm$trust_u0 <- effects.trustmed_full.gm$countrynew.Estimate.Intercept
effects.trustmed_full.gm$vac_m2.5 <- effects.trustmed_full.gm$countrynew.Q2.5.Intercept
effects.trustmed_full.gm$vac_m97.5 <- effects.trustmed_full.gm$countrynew.Q97.5.Intercept
effects.trustmed_full.gm$trust_u1 <- effects.trustmed_full.gm$countrynew.Estimate.sigma_Intercept
effects.trustmed_full.gm$vac_sd2.5 <- effects.trustmed_full.gm$countrynew.Q2.5.sigma_Intercept
effects.trustmed_full.gm$vac_sd97.5 <- effects.trustmed_full.gm$countrynew.Q97.5.sigma_Intercept
effects.trustmed_full.gm <- effects.trustmed_full.gm %>%
subset(select = c(Country, trust_u0, trust_u1))
wellcome.effects.med <-merge(wellcome.country, effects.trustmed_full.gm, by.x = "country", by.y = "Country", all.x=TRUE, all.y=TRUE)
bin.1.med <- glmer(vaccine_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
summary(bin.1.med)
bin.2.med <- glmer(vaccine_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
summary(bin.2.med)
bin.1.child.med <- glmer(vac_child_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
bin.2.child.med <- glmer(vac_child_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
bin.1.safe.med <- glmer(vac_safe_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
bin.2.safe.med <- glmer(vac_safe_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
bin.1.effect.med <- glmer(vac_effect_bin2 ~ trust_science_full + trust_u0 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
bin.2.effect.med <- glmer(vac_effect_bin2 ~ trust_science_full + trust_u0*trust_u1 + trust_science_full*trust_u1 + (1 | countrynew), family = binomial("logit"), nAGQ=15, data = wellcome.effects.med)
summary(bin.1.child.med)
summary(bin.2.child.med)
summary(bin.1.safe.med)
summary(bin.2.safe.med)
summary(bin.1.effect.med)
summary(bin.2.effect.med)
|
7ec5b431c7ea95c90c48f8ec6de9d7a002ac0afd
|
[
"R"
] | 1 |
R
|
luizgualmeida/Trust-in-science-social-consensus-and-vaccine-confidence
|
50a53bf0250c68e4cfde4288d19b3921f1034ba4
|
86799cecce178cc075ece53b2e6c9a0452028e88
|
refs/heads/master
|
<repo_name>pluggedinn/Tracka<file_sep>/README.md
# Tracka
- See how many hours you spend on your installed social apps
- Be able to set starting and end time of the period (default: 1 day, yesterday)
- Give suggestions of what you could have done in that time
<file_sep>/src/main/java/com/example/rsons/tracka/MainActivity.java
package com.example.rsons.tracka;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.example.rsons.tracka.service.MyReceiver;
import com.example.rsons.tracka.service.SessionService;
import java.io.File;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity {
TextView text1;
MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.text);
// Checking & asking if the user has access to settings
requestUsageStatsPermission();
// Starting service that tracks all the apps
Intent intent = new Intent(this, SessionService.class);
startService(intent);
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
@Override
protected void onStop() {
super.onStop();
}
void requestUsageStatsPermission() {
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
&& !hasUsageStatsPermission(this)) {
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
boolean hasUsageStatsPermission(Context context) {
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow("android:get_usage_stats",
android.os.Process.myUid(), context.getPackageName());
boolean granted = mode == AppOpsManager.MODE_ALLOWED;
return granted;
}
public void clickShowSessions(View v) {
File dbFile = this.getDatabasePath("TrackaDB");
SQLiteDatabase myDB = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, MODE_PRIVATE);
Cursor result = myDB.rawQuery("Select * from Sessions",null);
StringBuilder builder = new StringBuilder();
int rowsCount = result.getCount();
builder.append("sessions: " + rowsCount + "\n");
result.moveToFirst();
for(int i = 0; i < rowsCount; i++) {
builder.append(result.getLong(0) + " " + result.getLong(1) + " " + result.getLong(2) + " " + Utils.convertMillisToTime(result.getLong(1)) + "\n");
result.moveToNext();
}
text1.setText(builder.toString());
}
public void clickPastActivity(View v) {
Intent intent = new Intent(this, PastActivity.class);
startActivity(intent);
}
public void clickHomeActivity(View v) {
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
}
}
<file_sep>/src/main/java/com/example/rsons/tracka/model/Session.java
package com.example.rsons.tracka.model;
import com.example.rsons.tracka.Utils;
/**
* Created by rsons on 3/28/2017.
*/
public class Session {
public int appCode;
public long startTime;
public long endTime;
public Session (int _appCode, long _startTime, long _endTime) {
appCode = _appCode;
startTime = _startTime;
endTime = _endTime;
}
public String getDuration(){
return Utils.convertMillisToDuration(endTime - startTime);
}
}
<file_sep>/src/main/java/com/example/rsons/tracka/model/PastHeaderModel.java
package com.example.rsons.tracka.model;
import android.content.Context;
import android.util.Log;
import android.widget.RelativeLayout;
import com.airbnb.epoxy.EpoxyModel;
import com.example.rsons.tracka.R;
import com.example.rsons.tracka.SessionsRetriever;
import com.example.rsons.tracka.adapter.PastAdapter;
import com.example.rsons.tracka.formatter.AppFormatter;
import com.squareup.timessquare.CalendarPickerView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by rsons on 4/6/2017.
*/
public class PastHeaderModel extends EpoxyModel<RelativeLayout> {
private PastAdapter eAdapter;
private Context context;
private List<Date> selectedDates;
@BindView(R.id.calendarView) CalendarPickerView calendar;
public PastHeaderModel(PastAdapter eAdapter) {
this.eAdapter = eAdapter;
}
@Override
protected int getDefaultLayout() {
return R.layout.cell_header_past;
}
@Override
public void bind(RelativeLayout view) {
ButterKnife.bind(this, view);
context = calendar.getContext();
// Creating default dates for the Calendar picker
Calendar lastYear = Calendar.getInstance();
Calendar today = Calendar.getInstance();
Calendar yesterday = Calendar.getInstance();
Calendar previousDay = Calendar.getInstance();
lastYear.add(Calendar.YEAR, -1);
previousDay.add(Calendar.DATE, -2);
yesterday.add(Calendar.DATE, -1);
// Adding default dates to the calendar if not already set by the user
if (selectedDates == null) {
selectedDates = new ArrayList<>();
selectedDates.add(previousDay.getTime());
selectedDates.add(yesterday.getTime());
}
calendar.init(lastYear.getTime(), today.getTime())
.inMode(CalendarPickerView.SelectionMode.RANGE)
.withSelectedDates(selectedDates);
// Initializing session retriever
final SessionsRetriever dataRetriever = new SessionsRetriever(context);
calendar.setOnDateSelectedListener(new CalendarPickerView.OnDateSelectedListener() {
@Override
public void onDateSelected(Date date) {
// getting selected dates
selectedDates = calendar.getSelectedDates();
// clearing adapter
eAdapter.clearApps();
if (selectedDates.size() == 1) {
Calendar dayAfter = Calendar.getInstance();
dayAfter.setTime(date);
dayAfter.add(Calendar.DATE, 1);
List<Session> data = dataRetriever.getSessionsAllApps(date.getTime(), dayAfter.getTimeInMillis());
// Adding apps to the adapter
eAdapter.addApps(AppFormatter.createApps(data), date, dayAfter.getTime());
Log.d("DATA", data.size() + data.toString());
Log.d("START", date.toString());
Log.d("END", dayAfter.getTime()+"");
} else {
Calendar lastDay = Calendar.getInstance();
lastDay.setTime(selectedDates.get(selectedDates.size() - 1));
lastDay.add(Calendar.DATE, 1);
List<Session> data = dataRetriever.getSessionsAllApps(selectedDates.get(0).getTime(), lastDay.getTimeInMillis());
// Adding apps to the adapter
eAdapter.addApps(AppFormatter.createApps(data), selectedDates.get(0), lastDay.getTime());
Log.d("START", selectedDates.get(0).toString()+"");
Log.d("END", lastDay.getTime()+"");
Log.d("DATA", data.size() + data.toString());
}
}
@Override
public void onDateUnselected(Date date) {
}
});
}
}
<file_sep>/src/main/java/com/example/rsons/tracka/adapter/PastAdapter.java
package com.example.rsons.tracka.adapter;
import com.airbnb.epoxy.EpoxyAdapter;
import com.example.rsons.tracka.model.App;
import com.example.rsons.tracka.model.AppModel;
import com.example.rsons.tracka.model.PastHeaderModel;
import com.example.rsons.tracka.model.ToolbarModel;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created by rsons on 4/6/2017.
*/
public class PastAdapter extends EpoxyAdapter {
private ToolbarModel toolbarModel;
private PastHeaderModel headerModel;
public PastAdapter() {
enableDiffing();
toolbarModel = new ToolbarModel("-2");
headerModel = new PastHeaderModel(this);
addModels(toolbarModel, headerModel);
notifyModelsChanged();
}
public void addApps(HashMap<Integer, App> apps, Date start, Date end) {
for (Integer i : apps.keySet()) {
addModel(new AppModel(apps.get(i), start, end));
}
notifyModelsChanged();
}
public void clearApps() {
int currSize = models.size();
for(int i = 2; i < currSize; i++) {
models.remove(2);
}
notifyModelsChanged();
}
}
<file_sep>/src/main/java/com/example/rsons/tracka/service/SessionService.java
package com.example.rsons.tracka.service;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.icu.util.Calendar;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import com.example.rsons.tracka.R;
import com.rvalerio.fgchecker.AppChecker;
import java.util.Date;
/**
* Created by rsons on 3/20/2017.
*/
// TODO: create color strings so that can be accessed from anywhere. here is hard coded
public class SessionService extends IntentService {
/*
- 1: none
0: katana
1: instagram
2: snapchat
3: twitter
4: youtube
*/
int lastAppOpened = -1;
long currAppStartTime;
boolean katanaFlag;
boolean instagramFlag;
boolean snapchatFlag;
boolean twitterFlag;
boolean youtubeFlag;
SQLiteDatabase database;
Context context;
AppChecker appChecker;
Handler handler;
Runnable runnable;
MyReceiver receiver;
private String ACTION_STOP_SERVICE = "0";
private String ACTION_START_HANDLER = "1";
private String ACTION_STOP_HANDLER = "2";
public SessionService() {
super("Sessions Recorder");
}
@Override
public void onCreate() {
super.onCreate();
// Registering receiver that tracks if the screen is on
receiver = new MyReceiver();
IntentFilter lockFilter = new IntentFilter();
lockFilter.addAction(Intent.ACTION_SCREEN_ON);
lockFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(receiver, lockFilter);
// Initializing the database
database = openOrCreateDatabase("TrackaDB",MODE_PRIVATE,null);
database.execSQL("CREATE TABLE IF NOT EXISTS Sessions(package INTEGER, startTime LONG, endTime LONG);");
// Initializing the handler that will contain the Runnable AppCheckerThread
handler = new Handler();
Log.d("TrackaService", "Service created...");
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
// Checking if ACTION_STOP_SERVICE event is triggered
if (intent != null) {
if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
Log.d("TrackaService", "...called to cancel service...");
// Deleting foreground notification
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.cancel(1192);
// Stopping service and calling onDestroy()
stopSelf();
Log.d("TrackaService", "...returning start_not_sticky");
return START_NOT_STICKY;
}
}
// ... continuing with the execution of the Service
context = this;
Log.d("TrackaService", "Service started...");
// Setting the action when the user taps on the notification
Intent stopSelf = new Intent(this, SessionService.class);
stopSelf.setAction(this.ACTION_STOP_SERVICE);
PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf, PendingIntent.FLAG_CANCEL_CURRENT);
// Creating notification and starting service in Foreground
Notification notification = new NotificationCompat.Builder(this)
.setContentText("Running, tap to stop")
.setSmallIcon(R.mipmap.ic_minimal)
.setColor(Color.parseColor("#0B486B"))
.setPriority(Notification.PRIORITY_MIN)
//.setShowWhen(false)
.setContentIntent(pStopSelf)
.setOngoing(true).build();
startForeground(1192, notification);
// Starting the loop that looks for apps opened and closed depending on the event
if (ACTION_START_HANDLER.equals(intent.getAction())) {
startAppCheckerThread();
} else if (ACTION_STOP_HANDLER.equals(intent.getAction())) {
stopAppCheckerThread();
} else {
startAppCheckerThread();
}
Log.d("TrackaService", "...returning start_sticky");
return START_STICKY;
}
/**
* Starts the thread loop that checks the apps.
*/
public void startAppCheckerThread() {
final int delay = 1000; // milliseconds
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
runnable = new Runnable(){
public void run(){
appChecker = new AppChecker();
String packageName = appChecker.getForegroundApp(context);
boolean isScreenOn = pm.isInteractive();
// Checking if the packagename string is not null
if (packageName != null && !packageName.isEmpty()) {
if (packageName.contains("com.facebook.katana") && isScreenOn) {
if (lastAppOpened != 0) {
processFlags();
}
if (!katanaFlag) {
Log.d("TrackaService", "FACEBOOK started");
katanaFlag = true;
lastAppOpened = 0;
currAppStartTime = new Date().getTime();
}
} else if (packageName.contains("com.instagram.android") && isScreenOn) {
if (lastAppOpened != 1) {
processFlags();
}
if (!instagramFlag) {
Log.d("TrackaService", "INSTAGRAM started");
instagramFlag = true;
lastAppOpened = 1;
currAppStartTime = new Date().getTime();
}
} else if (packageName.contains("com.snapchat.android") && isScreenOn) {
if (lastAppOpened != 2) {
processFlags();
}
if (!snapchatFlag) {
Log.d("TrackaService", "SNAPCHAT started");
snapchatFlag = true;
lastAppOpened = 2;
currAppStartTime = new Date().getTime();
}
} else if (packageName.contains("com.twitter.android") && isScreenOn) {
if (lastAppOpened != 3) {
processFlags();
}
if (!twitterFlag) {
Log.d("TrackaService", "TWITTER started");
twitterFlag = true;
lastAppOpened = 3;
currAppStartTime = new Date().getTime();
}
} else if (packageName.contains("com.google.android.youtube") && isScreenOn) {
if (lastAppOpened != 4) {
processFlags();
}
if (!youtubeFlag) {
Log.d("TrackaService", "YOUTUBE started");
youtubeFlag = true;
lastAppOpened = 4;
currAppStartTime = new Date().getTime();
}
} else {
processFlags();
lastAppOpened = -1;
}
}
// Restarting this runnable at the delay
handler.postDelayed(runnable, delay);
}
};
handler.post(runnable);
Log.d("TrackaService", "...handler started...");
}
/**
* Kills the thread loop that checks all the apps.
*/
public void stopAppCheckerThread() {
processFlags();
if (runnable != null) {
handler.removeCallbacks(runnable);
}
Log.d("TrackaService", "...handler stopped...");
}
/**
* Call this method if you want to stop recording the foreground app want to register it to the databse.
*
* When any of the flags are on it means that the one of those apps have been open.
* When you run this method you notify Tracka that the app have been closed (or the foreground app has been changed)
* and then you write into the database the Session of the app just closed.
*/
public void processFlags() {
if (katanaFlag) {
Log.d("TrackaService", "FACEBOOK stopped");
katanaFlag = false;
String query = "INSERT INTO Sessions VALUES('0','"+currAppStartTime+"','"+new Date().getTime()+"');";
database.execSQL(query);
Cursor cursor = database.rawQuery("Select * from Sessions",null);
Log.d("TrackaService", cursor.getCount() + " sessions total");
cursor.close();
}
if (instagramFlag) {
Log.d("TrackaService", "INSTAGRAM stopped");
instagramFlag = false;
String query = "INSERT INTO Sessions VALUES('1','"+currAppStartTime+"','"+new Date().getTime()+"');";
database.execSQL(query);
Cursor cursor = database.rawQuery("Select * from Sessions",null);
Log.d("TrackaService", cursor.getCount() + " sessions total");
cursor.close();
}
if (snapchatFlag) {
Log.d("TrackaService", "SNAPCHAT stopped");
snapchatFlag = false;
String query = "INSERT INTO Sessions VALUES('2','"+currAppStartTime+"','"+new Date().getTime()+"');";
database.execSQL(query);
Cursor cursor = database.rawQuery("Select * from Sessions",null);
Log.d("TrackaService", cursor.getCount() + " sessions total");
cursor.close();
}
if (twitterFlag) {
Log.d("TrackaService", "TWITTER stopped");
twitterFlag = false;
String query = "INSERT INTO Sessions VALUES('3','"+currAppStartTime+"','"+new Date().getTime()+"');";
database.execSQL(query);
Cursor cursor = database.rawQuery("Select * from Sessions",null);
Log.d("TrackaService", cursor.getCount() + " sessions total");
cursor.close();
}
if (youtubeFlag) {
Log.d("TrackaService", "YOUTUBE stopped");
youtubeFlag = false;
String query = "INSERT INTO Sessions VALUES('4','"+currAppStartTime+"','"+new Date().getTime()+"');";
database.execSQL(query);
Cursor cursor = database.rawQuery("Select * from Sessions",null);
Log.d("TrackaService", cursor.getCount() + " sessions total");
cursor.close();
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopAppCheckerThread();
unregisterReceiver(receiver);
Log.d("TrackaService", "...Service destroyed");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
}
}
|
2b59b7aa2d80dd091d466347a24ff0c488e7625b
|
[
"Java",
"Markdown"
] | 6 |
Java
|
pluggedinn/Tracka
|
1ecaba02748879624104bca17e8330bf52167572
|
d6acbc8d55cf81b6a00b60c17dcf586560f2a990
|
refs/heads/main
|
<repo_name>melander2910/midipiano<file_sep>/sound.js
let hihat = new Tone.Player("./samples/CYCdh_K1close_ClHat-01.wav").toDestination();
let snare = new Tone.Player("./samples/CYCdh_K1close_Snr-01.wav").toDestination();
let rim = new Tone.Player("./samples/CYCdh_K1close_Rim-01.wav").toDestination();
let sdst = new Tone.Player("./samples/CYCdh_K1close_SdSt-01.wav").toDestination();
let kick = new Tone.Player("./samples/CYCdh_K1close_Kick-03.wav").toDestination();
function sequencer() {
let checkbox = 0;
Tone.Transport.bpm.value = 80;
Tone.Master.volume.value = -10;
Tone.Transport.scheduleRepeat(repeat, "16n")
Tone.Transport.start();
function repeat(time) {
let step = checkbox % 16;
let selectedSound1 = document.querySelector(`.top input:nth-child(${step + 1})`);
let selectedSound2 = document.querySelector(`.middle-1 input:nth-child(${step + 1})`);
let selectedSound3 = document.querySelector(`.middle-2 input:nth-child(${step + 1})`);
let selectedSound4 = document.querySelector(`.middle-3 input:nth-child(${step + 1})`);
let selectedSound5 = document.querySelector(`.bottom input:nth-child(${step + 1})`);
if (selectedSound1.checked) {
hihat.start(time).stop(time + 0.1);
}
if (selectedSound2.checked) {
snare.start(time).stop(time + 0.1);
}
if (selectedSound3.checked) {
rim.start(time).stop(time + 0.1);
}
if (selectedSound4.checked) {
sdst.start(time).stop(time + 0.1);
}
if (selectedSound5.checked) {
kick.start(time).stop(time + 0.1);
}
checkbox++
}
}
sequencer();
// -- start/stop drum machine start --
let on = false;
document.getElementById("play").addEventListener("click", () => {
if (!on) {
Tone.Transport.start()
Tone.start();
on = true;
} else {
Tone.Transport.start().stop();
on = false;
}
})
// -- start/stop drum machine end --
if (navigator.requestMIDIAccess) {
console.log('This browser supports WebMIDI!');
} else {
console.log('WebMIDI is not supported in this browser.');
}
navigator.requestMIDIAccess()
.then(onMIDISuccess, onMIDIFailure);
function onMIDISuccess(midiAccess) {
console.log(midiAccess);
let inputs = midiAccess.inputs;
let outputs = midiAccess.outputs;
}
function onMIDIFailure() {
console.log('Could not access your MIDI devices.');
}
function onMIDISuccess(midiAccess) {
for (let input of midiAccess.inputs.values())
input.onmidimessage = getMIDIMessage;
}
function getMIDIMessage(message) {
let command = message.data[0];
let noteNumber = message.data[1];
let velocity = (message.data.length > 2) ? message.data[2] : 0;
console.log(command, noteNumber, velocity);
playMidi(noteNumber, command, sampler, sustain);
}
// Tone sampler laver et instrument ud fra disse samples
let sampler = new Tone.Sampler({
urls: {
"C4": "C4.mp3",
"D#4": "Ds4.mp3",
"F#4": "Fs4.mp3",
"A4": "A4.mp3",
},
release: 1,
baseUrl: "/pianoNotes/",
}).toDestination();
// -- Sustain slider start --
let slider = document.getElementById("sustainpedal");
let output = document.getElementById("sustainlength");
let sustain = slider.value
output.innerHTML = slider.value;
slider.oninput = () => {
sustain = slider.value
output.innerHTML = sustain;
}
// -- Sustain slider end --
// -- BPM slider start --
let bpm = document.getElementById("bpm");
let bpmOutput = document.getElementById("bpmValue");
let bpmValue = bpm.value
bpmOutput.innerHTML = bpm.value;
bpm.oninput = () => {
bpmValue = bpm.value
bpmOutput.innerHTML = bpmValue;
Tone.Transport.bpm.value = bpmValue;
}
// -- BPM slider end --
// let bpmClock = 1;
// let clock = new Tone.Clock(time => {
// console.log(time);
// }, bpmClock)
// clock.start();
function piano() {
// Clicking the piano to play
const notes = document.querySelectorAll('.note')
let mousedown = false;
notes.forEach(note => {
note.addEventListener("mousedown", () => {
play(note, sampler, sustain)
mousedown = true;
})
note.addEventListener("mouseenter", () => {
if(mousedown){
play(note, sampler, sustain)
}
})
note.addEventListener("mouseup", () => {
mousedown = false;
})
})
}
function play(note, sampler, sustain) {
sampler.triggerAttackRelease(note.id, sustain, Tone.context.currentTime);
note.classList.add("active");
setTimeout(() =>{
note.classList.remove("active");
}, 100)
}
piano();
function playMidi(noteNumber, command, sampler, sustain) {
let id = document.getElementsByName(noteNumber)[0].getAttribute("id");
if (command == 144) {
document.getElementById(id).classList.add("active");
sampler.triggerAttackRelease(id, sustain, Tone.context.currentTime)
console.log(sustain);
}
if (command == 128) {
document.getElementById(id).classList.remove("active");
}
}
document.addEventListener("keydown", (event) => {
console.log(event.key);
if(event.repeat) return
if (event.key == "q") {
sampler.triggerAttackRelease(["C3"], sustain, Tone.context.currentTime);
document.getElementById("C3").classList.add("active");
setTimeout(() => {
document.getElementById("C3").classList.remove("active");
}, 200)
}
if (event.key == "2") {
sampler.triggerAttackRelease(["C#3"], sustain, Tone.context.currentTime);
document.getElementById("C#3").classList.add("active");
setTimeout(() => {
document.getElementById("C#3").classList.remove("active");
}, 200)
}
if (event.key == "w") {
sampler.triggerAttackRelease(["D3"], sustain, Tone.context.currentTime);
document.getElementById("D3").classList.add("active");
setTimeout(() => {
document.getElementById("D3").classList.remove("active");
}, 200)
}
if (event.key == "3") {
sampler.triggerAttackRelease(["D#3"], sustain, Tone.context.currentTime);
document.getElementById("D#3").classList.add("active");
setTimeout(() => {
document.getElementById("D#3").classList.remove("active");
}, 200)
}
if (event.key == "e") {
sampler.triggerAttackRelease(["E3"], sustain, Tone.context.currentTime);
document.getElementById("E3").classList.add("active");
setTimeout(() => {
document.getElementById("E3").classList.remove("active");
}, 200)
}
if (event.key == "4") {
sampler.triggerAttackRelease(["F3"], sustain, Tone.context.currentTime);
document.getElementById("F3").classList.add("active");
setTimeout(() => {
document.getElementById("F3").classList.remove("active");
}, 200)
}
if (event.key == "r") {
sampler.triggerAttackRelease(["F#3"], sustain, Tone.context.currentTime);
document.getElementById("F#3").classList.add("active");
setTimeout(() => {
document.getElementById("F#3").classList.remove("active");
}, 200)
}
if (event.key == "5") {
sampler.triggerAttackRelease(["G3"], sustain, Tone.context.currentTime);
document.getElementById("G3").classList.add("active");
setTimeout(() => {
document.getElementById("G3").classList.remove("active");
}, 200)
}
if (event.key == "t") {
sampler.triggerAttackRelease(["G#3"], sustain, Tone.context.currentTime);
document.getElementById("G#3").classList.add("active");
setTimeout(() => {
document.getElementById("G#3").classList.remove("active");
}, 200)
}
if (event.key == "6") {
sampler.triggerAttackRelease(["A3"], sustain, Tone.context.currentTime);
document.getElementById("A3").classList.add("active");
setTimeout(() => {
document.getElementById("A3").classList.remove("active");
}, 200)
}
if (event.key == "y") {
sampler.triggerAttackRelease(["A#3"], sustain, Tone.context.currentTime);
document.getElementById("A#3").classList.add("active");
setTimeout(() => {
document.getElementById("A#3").classList.remove("active");
}, 200)
}
if (event.key == "7") {
sampler.triggerAttackRelease(["B3"], sustain, Tone.context.currentTime);
document.getElementById("B3").classList.add("active");
setTimeout(() => {
document.getElementById("B3").classList.remove("active");
}, 200)
}
if (event.key == "u") {
sampler.triggerAttackRelease(["C4"], sustain, Tone.context.currentTime);
document.getElementById("C4").classList.add("active");
setTimeout(() => {
document.getElementById("C4").classList.remove("active");
}, 200)
}
if (event.key == "8") {
sampler.triggerAttackRelease(["C#4"], sustain, Tone.context.currentTime);
document.getElementById("C#4").classList.add("active");
setTimeout(() => {
document.getElementById("C#4").classList.remove("active");
}, 200)
}
if (event.key == "i") {
sampler.triggerAttackRelease(["D4"], sustain, Tone.context.currentTime);
document.getElementById("D4").classList.add("active");
setTimeout(() => {
document.getElementById("D4").classList.remove("active");
}, 200)
}
if (event.key == "9") {
sampler.triggerAttackRelease(["D#4"], sustain, Tone.context.currentTime);
document.getElementById("D#4").classList.add("active");
setTimeout(() => {
document.getElementById("D#4").classList.remove("active");
}, 200)
}
if (event.key == "o") {
sampler.triggerAttackRelease(["E4"], sustain, Tone.context.currentTime);
document.getElementById("E4").classList.add("active");
setTimeout(() => {
document.getElementById("E4").classList.remove("active");
}, 200)
}
if (event.key == "0") {
sampler.triggerAttackRelease(["F4"], sustain, Tone.context.currentTime);
document.getElementById("F4").classList.add("active");
setTimeout(() => {
document.getElementById("F4").classList.remove("active");
}, 200)
}
if (event.key == "p") {
sampler.triggerAttackRelease(["F#4"], sustain, Tone.context.currentTime);
document.getElementById("F#4").classList.add("active");
setTimeout(() => {
document.getElementById("F#4").classList.remove("active");
}, 200)
}
if (event.key == "z") {
sampler.triggerAttackRelease(["G4"], sustain, Tone.context.currentTime);
document.getElementById("G4").classList.add("active");
setTimeout(() => {
document.getElementById("G4").classList.remove("active");
}, 200)
}
if (event.key == "s") {
sampler.triggerAttackRelease(["G#4"], sustain, Tone.context.currentTime);
document.getElementById("G#4").classList.add("active");
setTimeout(() => {
document.getElementById("G#4").classList.remove("active");
}, 200)
}
if (event.key == "x") {
sampler.triggerAttackRelease(["A4"], sustain, Tone.context.currentTime);
document.getElementById("A4").classList.add("active");
setTimeout(() => {
document.getElementById("A4").classList.remove("active");
}, 200)
}
if (event.key == "d") {
sampler.triggerAttackRelease(["A#4"], sustain, Tone.context.currentTime);
document.getElementById("A#4").classList.add("active");
setTimeout(() => {
document.getElementById("A#4").classList.remove("active");
}, 200)
}
if (event.key == "c") {
sampler.triggerAttackRelease(["B4"], sustain, Tone.context.currentTime);
document.getElementById("B4").classList.add("active");
setTimeout(() => {
document.getElementById("B4").classList.remove("active");
}, 200)
}
})
// -- change sound to bass start --
document.getElementById("bassSound").addEventListener("click", () => {
sampler = new Tone.Sampler({
urls: {
"A#4": "As4.mp3",
"C#4": "Cs4.mp3",
"E4": "E4.mp3",
"G4": "G4.mp3",
},
release: 1,
baseUrl: "/bassNotes/",
}).toDestination();
})
// -- change sound to bass end --
// -- change sound to acoustic guitar start --
document.getElementById("a-GuitarSound").addEventListener("click", () => {
sampler = new Tone.Sampler({
urls: {
"A3": "A3.mp3",
"B3": "B3.mp3",
"C4": "C4.mp3",
"C#4": "Cs4.mp3",
},
release: 1,
baseUrl: "/aGuitarNotes/",
}).toDestination();
})
// -- change sound to acoustic guitar end --
// -- change sound to flute start --
document.getElementById("fluteSound").addEventListener("click", () => {
sampler = new Tone.Sampler({
urls: {
"C4": "C4.mp3",
"E4": "E4.mp3",
"A4": "A4.mp3",
},
release: 1,
baseUrl: "/fluteNotes/",
}).toDestination();
})
// -- change sound to flute end --
function changeSound(id, url){
document.getElementById(id).addEventListener("click", () => {
sampler = new Tone.Sampler({
urls: {
"C4": "C4.mp3",
"D#4": "Ds4.mp3",
"F#4": "Fs4.mp3",
"A4": "A4.mp3",
},
release: 1,
baseUrl: url,
}).toDestination();
})
}
changeSound("celloSound", "/celloNotes/");
changeSound("pianoSound", "/pianoNotes/");
changeSound("saxophoneSound", "/saxNotes/");
changeSound("e-GuitarSound", "/eGuitarNotes/");
// -- hithat select start --
document.getElementById("hihatselect").addEventListener("change", () => {
let value = document.getElementById("hihatselect").value;
Tone.Transport.start();
console.log(value);
if(value == 1){
console.log(value);
hihat = new Tone.Player("./samples/CYCdh_K1close_ClHat-01.wav").toDestination();
}
else if(value == 2){
hihat = new Tone.Player("./samples/CYCdh_K1close_ClHat-05.wav").toDestination();
}
else if(value == 3){
hihat = new Tone.Player("./samples/CYCdh_K1close_ClHat-04.wav").toDestination();
}
else if(value == 4){
hihat = new Tone.Player("./samples/CYCdh_K1close_ClHat-08.wav").toDestination();
}
})
// -- hithat select end --
// -- snare select start --
document.getElementById("snareselect").addEventListener("change", () => {
Tone.Transport.start();
let value = document.getElementById("snareselect").value;
if(value == 1){
snare = new Tone.Player("./samples/CYCdh_K1close_Snr-02.wav").toDestination();
}
else if(value == 2){
snare = new Tone.Player("./samples/CYCdh_K1close_SnrOff-04.wav").toDestination();
}
else if(value == 3){
snare = new Tone.Player("./samples/CYCdh_K1close_Snr-03.wav").toDestination();
}
else if(value == 4){
snare = new Tone.Player("./samples/CYCdh_K1close_Snr-05.wav").toDestination();
}
})
// -- snare select end --
// -- rim select start --
document.getElementById("rimselect").addEventListener("change", () => {
Tone.Transport.start();
let value = document.getElementById("rimselect").value;
console.log(value);
if(value == 1){
rim = new Tone.Player("./samples/CYCdh_K1close_Rim-01.wav").toDestination();
}
else if(value == 2){
rim = new Tone.Player("./samples/CYCdh_K1close_Rim-05.wav").toDestination();
}
else if(value == 3){
rim = new Tone.Player("./samples/CYCdh_K1close_Rim-03.wav").toDestination();
}
else if(value == 4){
rim = new Tone.Player("./samples/CYCdh_K1close_Rim-04.wav").toDestination();
}
})
// -- rim select end --
// -- side select start --
document.getElementById("sideselect").addEventListener("change", () => {
Tone.Transport.start();
let value = document.getElementById("sideselect").value;
console.log(value);
if(value == 1){
sdst = new Tone.Player("./samples/CYCdh_K1close_SdSt-01.wav").toDestination();
}
else if(value == 2){
sdst = new Tone.Player("./samples/CYCdh_K1close_SdSt-03.wav").toDestination();
}
else if(value == 3){
sdst = new Tone.Player("./samples/CYCdh_K1close_SdSt-05.wav").toDestination();
}
else if(value == 4){
sdst = new Tone.Player("./samples/CYCdh_K1close_SdSt-07.wav").toDestination();
}
})
// -- side select end --
// -- kick select start --
document.getElementById("kickselect").addEventListener("change", () => {
let value = document.getElementById("kickselect").value;
console.log(value);
if(value == 1){
kick = new Tone.Player("./samples/CYCdh_K1close_Kick-03.wav").toDestination();
}
else if(value == 2){
kick = new Tone.Player("./samples/CYCdh_K1close_Kick-04.wav").toDestination();
}
else if(value == 3){
kick = new Tone.Player("./samples/CYCdh_K1close_Kick-07.wav").toDestination();
}
else if(value == 4){
kick = new Tone.Player("./samples/CYCdh_K1close_Kick-08.wav").toDestination();
}
})
// -- kick select end --
|
4cc6f5566ff882043689880ca7a30c4168ed9d97
|
[
"JavaScript"
] | 1 |
JavaScript
|
melander2910/midipiano
|
bc927dc750ce7b68cfbed06e168406c11901849d
|
9b50836a53d50437af10fd23ce6c603a83dc3a7a
|
refs/heads/master
|
<repo_name>singhalkul/s99<file_sep>/build.sbt
name := "S-99"
version := "1.0"
libraryDependencies ++= Seq(
"org.scalatest" % "scalatest_2.10" % "2.2.4" % "test"
)
<file_sep>/src/main/scala/com/s99/MyList.scala
package com.s99
import MyList._
import scala.util.Random
/**
* author: Kul
*/
class MyList[A](self: List[A]) {
def duplicateN(times: Int) = self myFlatMap { e => List.fill(times)(e) }
def duplicate = self myFlatMap (e => List(e, e))
def encodeDirect(): List[(Int, A)] = {
if (self isEmpty) Nil
else {
val (packed, rest) = self.mySpan(_ == self.head)
(packed, rest) match {
case (p, Nil) => List((p.size, p.head))
case (p, r) => (p.size, p.head) :: r.encodeDirect()
}
}
}
def runLengthEncoding() = {
if (self.isEmpty) List()
else self.pack() myMap { l => (l.size, l.head) }
}
def runLengthEncodingModified() = {
if (self.isEmpty) List()
else self.pack() myMap { l => if (l.size == 1) l.head else (l.size, l.head) }
}
def pack(): List[List[A]] = {
if (self isEmpty) List(Nil)
else {
val (packed, rest) = self.mySpan(a => a == self.head)
(packed, rest) match {
case (p, Nil) => List(p)
case (p, r) => p :: r.pack()
}
}
}
def compress(): List[A] = {
def compressR(list: List[A], result: List[A]): List[A] = (list, result) match {
case (Nil, res) => res
case (h :: tail, Nil) => compressR(tail, h :: Nil)
case (h :: tail, r :: resTail) if h == r => compressR(tail, result)
case (h :: tail, r :: resTail) => compressR(tail, h :: result)
}
compressR(self, Nil).myReverse()
}
private def flattenTailRecursive(result: List[A], input: List[A], remainingTail: List[A]): List[A] = input match {
case Nil if remainingTail == Nil => result
case Nil => flattenTailRecursive(result, remainingTail, Nil)
case (l: List[A]) :: tail => flattenTailRecursive(result, l, tail ::: remainingTail)
case h :: tail => flattenTailRecursive(h :: result, tail, remainingTail)
}
def myFlatten(): List[A] = flattenTailRecursive(Nil, self, Nil).myReverse()
def isPalindrome = {
def isPalindromeR(list: List[A], reversed: List[A]): Boolean = (list, reversed) match {
case (Nil, Nil) => true
case (Nil, _) | (_, Nil) => false
case (h1 :: tail1, h2 :: tail2) => h1 == h2 && isPalindromeR(tail1, tail2)
}
isPalindromeR(self, self.myReverse())
}
def myLength(): Int = {
def tailLength(list: List[A], result: Int): Int = list match {
case Nil => result
case h :: tail => tailLength(tail, result + 1)
}
tailLength(self, 0)
}
def myReverse(): List[A] = {
def tailReverse(input: List[A], result: List[A]): List[A] = input match {
case Nil => result
case h :: tail => tailReverse(tail, h :: result)
}
tailReverse(self, Nil)
}
def kth(k: Int): Option[A] = (k, self) match {
case (p, Nil) => None
case (0, h :: tail) => Some(h)
case (n, h :: tail) => tail.kth(n - 1)
}
def penultimate(): Option[A] = self match {
case a :: b :: Nil => Some(a)
case a :: tail => tail.penultimate()
case Nil => None
}
def dropN(n: Int) = self.myZipWithIndex.myFilter(t => (t._2 + 1) % n != 0).map(_._1)
def myLast(): Option[A] = self match {
case Nil => None
case a :: Nil => Some(a)
case a :: tail => tail.myLast()
}
def rotateLeft(n: Int): List[A] = if(n < 0) rotateLeft(self.size - n.abs) else self.myDrop(n) ::: self.myTake(n)
def mySpan(f: A => Boolean) = (self.myTakeWhile(f), self.myDropWhile(f))
def myTakeWhile(f: A => Boolean) = {
def takeWhileR(f: A => Boolean)(list: List[A], result: List[A]): List[A] = list match {
case Nil => result
case head :: tail if f(head) => takeWhileR(f)(tail, head :: result)
case head :: tail => result
}
takeWhileR(f)(self, Nil)
}
def myDropWhile(f: A => Boolean): List[A] = self match {
case Nil => Nil
case head :: (tail) if f(head) => tail.myDropWhile(f)
case head :: tail => head :: tail
}
def myMap[B](f: A => B): List[B] = {
def myMapR(f: A => B, list: List[A], result: List[B]): List[B] = list match {
case Nil => result
case head :: tail => myMapR(f, tail, f(head) :: result)
}
myMapR(f, self, Nil).reverse
}
def myFlatMap[B](f: A => Iterable[B]): Iterable[B] = {
def myFlatMapR(f: A => Iterable[B], list: List[A], result: Iterable[B]): Iterable[B] = {
list match {
case Nil => result
case head :: tail => myFlatMapR(f, tail, result ++ f(head))
}
}
myFlatMapR(f, self, Nil)
}
def myGrouped(group: Int): List[List[A]] = {
def groupedR(list: List[A], acc: List[A], count: Int, result: List[List[A]]): List[List[A]] = list match {
case Nil => List(acc)
case head :: Nil if group == count => List(acc) ++ List(List(head))
case head :: Nil => List(acc :+ head)
case head :: tail if group == count => groupedR(tail, head :: Nil, 0, result ++ List(acc))
case head :: tail => groupedR(tail, acc :+ head, count + 1, result)
}
groupedR(self, Nil, 0, Nil)
}
def myFilter(f: A => Boolean): List[A] = {
def myFilterR(f: A => Boolean, list: List[A], result: List[A]): List[A] = list match {
case Nil => result
case head :: tail => if(f(head)) myFilterR(f, tail, head :: result) else myFilterR(f, tail, result)
}
myFilterR(f, self, Nil).myReverse()
}
def myZipWithIndex: List[(A, Int)] = {
def myZipWithIndexR(list: List[A], index: Int, result: List[(A, Int)]): List[(A, Int)] = list match {
case Nil => result
case head :: tail => myZipWithIndexR(tail, index + 1, (head, index) :: result)
}
myZipWithIndexR(self, 0, Nil).myReverse()
}
def mySplit(n: Int): (List[A], List[A]) = {
def mySplitR(n: Int, list: List[A], result: List[A]): (List[A], List[A]) = {
(n, list) match {
case (0, _) => (result, list)
case (_, Nil) => (result, Nil)
case (_, head :: Nil) => (head :: result, Nil)
case (_, head :: tail) => mySplitR(n - 1, tail, head :: result)
}
}
val (first, second) = mySplitR(n, self, Nil)
(first.myReverse(), second)
}
def mySlice(from: Int, to: Int) = {
self.myDrop(from).myTake(to - from)
}
def myTake(n : Int) = {
def myTakeR(n: Int, list: List[A], result: List[A]): List[A] = {
(n, list) match {
case (0, _) | (_, Nil) => result
case (_, head :: tail) => myTakeR(n - 1, tail, head :: result)
}
}
if (n <= 0) Nil else myTakeR(n, self, Nil).myReverse()
}
def myDrop(n: Int) = {
def myDropR(n: Int, list: List[A], result: List[A]): List[A] = {
(n, list) match {
case (0, _) | (_, Nil)=> result
case(_, head :: tail) => myDropR(n - 1, tail, tail)
}
}
if(n <= 0) self else myDropR(n, self, Nil)
}
def removeKthElement(k: Int) = {
val (first, second) = self.mySplit(k)
(first ::: second.tail, second. head)
}
def insertAt(k: Int, a: A) = {
val (first, second) = self.mySplit(k)
first ::: a :: second
}
def randomDelete(count: Int) = {
val random = new Random()
def randomDeleteR(count: Int, list: List[A], result: List[A]): List[A] = {
if(count == 0) result else {
val k = random.nextInt(list.size)
val (rest, deleted) = list.removeKthElement(k)
randomDeleteR(count - 1, rest, deleted :: result)
}
}
randomDeleteR(count, self, Nil)
}
}
object MyList {
implicit def enhancedList[T](self: List[T]): MyList[T] = new MyList(self)
def createListForRange(from: Int, to: Int) = {
def createR(from: Int, to: Int, result: List[Int]): List[Int] = {
if(from == to) from :: result
else createR(from, to - 1, to :: result)
}
createR(from, to, Nil)
}
def lotto(k: Int, maxRange: Int) = {
createListForRange(1, maxRange).randomDelete(k)
}
}<file_sep>/src/test/scala/com/s99/MyListTest.scala
package com.s99
import com.s99.MyList._
import org.scalatest.{FunSpec, Matchers}
/**
* author: Kul.
*/
class MyListTest extends FunSpec with Matchers {
describe("Scala 99 problems") {
describe("01. finding the last element of list") {
it("should return last element from a list") {
List(1, 2, 3, 4, 5).myLast() shouldEqual Some(5)
}
it("should return None") {
Nil.myLast() shouldEqual None
}
}
describe("02. finding penultimate element of list") {
it("should return None if list is empty") {
Nil.penultimate() shouldEqual None
}
it("should return None of list size is 1") {
List(1).penultimate() shouldEqual None
}
it("should return the penultimate element from a list of size of 2 elements") {
List(2, 3).penultimate() shouldEqual Some(2)
}
it("should return the penultimate element from a list of size of 3 elements") {
List(1, 2, 3).penultimate() shouldEqual Some(2)
}
it("should return the penultimate element from a list of size greater than 3 elements") {
List(1, 2, 3, 4, 5).penultimate() shouldEqual Some(4)
}
}
describe("03. finding kth element of list") {
it("should return None if list is empty") {
Nil.kth(1) shouldEqual None
}
it("should return the kth for list of size 1") {
List(1).kth(0) shouldEqual Some(1)
}
it("should return the 1st for list of size 2") {
List(1, 2).kth(0) shouldEqual Some(1)
}
it("should return the 2nd for list of size 2") {
List(1, 2).kth(1) shouldEqual Some(2)
}
it("should return the 4th for list of size 6") {
List(1, 2, 3, 4, 5, 6).kth(3) shouldEqual Some(4)
}
}
describe("04. reversing a list should reverse") {
it("Nil for empty list") {
Nil.myReverse() shouldEqual Nil
}
it("list of size 1") {
List(1).myReverse() shouldEqual List(1)
}
it("list of size 2") {
List(1, 2).myReverse() shouldEqual List(2, 1)
}
it("list of size greater than 2") {
List(1, 2, 3, 4, 5).myReverse() shouldEqual List(5, 4, 3, 2, 1)
}
}
describe("05. finding length of list") {
it("should return 0 for empty list") {
Nil.myLength() shouldEqual 0
}
it("should return 1 for list of size 1") {
List(1).myLength() shouldEqual 1
}
it("should return 2 for list of size 2") {
List(1, 2).myLength() shouldEqual 2
}
it("should return 5 for list of size 5") {
List(1, 2, 3, 4, 5).myLength() shouldEqual 5
}
}
describe("06. checking whether a list is palindrome") {
it("should return true for empty list") {
Nil.isPalindrome shouldEqual (right = true)
}
it("should return true for list with one element") {
List(1).isPalindrome shouldEqual (right = true)
}
it("should return false for list 1,2") {
List(1, 2).isPalindrome shouldEqual (right = false)
}
it("should return true for list 1,2,1,2,1") {
List(1, 2, 1, 2, 1).isPalindrome shouldEqual (right = true)
}
it("should return false for list 1,2,3") {
List(1, 2, 3).isPalindrome shouldEqual (right = false)
}
}
describe("07. flattening a list") {
it("should return Nil for empty list") {
Nil.myFlatten() shouldEqual Nil
}
it("should return same list for List(1,2,3") {
List(1, 2, 3).myFlatten() shouldEqual List(1, 2, 3)
}
it("should return flattened list for List(1,List(2,3,4),3)") {
List(1, List(2, 3, 4), 3).myFlatten() shouldEqual List(1, 2, 3, 4, 3)
}
it("should return flattened list for List(List(List(2)))") {
List(List(List(2))).myFlatten() shouldEqual List(2)
}
it("should return flattened list for List(List(List(1,2)), 3)") {
List(List(List(1, 2)), 3).myFlatten() shouldEqual List(1, 2, 3)
}
}
describe("08. removing consecutive duplicates from a list") {
it("should return Nil from empty list") {
Nil.compress() shouldEqual Nil
}
it("should return List(1) for List(1)") {
List(1).compress() shouldEqual List(1)
}
it("should return List(1) for List(1,1)") {
List(1, 1).compress() shouldEqual List(1)
}
it("should return List(1,2) for List(1,2)") {
List(1, 2).compress() shouldEqual List(1, 2)
}
it("should return compressed list") {
List(1, 1, 1, 1, 2, 3, 3, 1, 1, 4, 5, 5, 5, 5).compress() shouldEqual List(1, 2, 3, 1, 4, 5)
}
}
describe("09. packing consecutive duplicates") {
it("should return List of Nil for empty List") {
Nil.pack() shouldEqual List(Nil)
}
it("should return List(List(1)) for List(1)") {
List(1).pack() shouldEqual List(List(1))
}
it("should return List(List(1), List(2)) for List(1,2)") {
List(1, 2).pack() shouldEqual List(List(1), List(2))
}
it("should return List(List(1,1,1), List(2,2), List(1)) for List(1,1,1,2,2,1)") {
List(1, 1, 1, 2, 2, 1).pack() shouldEqual List(List(1, 1, 1), List(2, 2), List(1))
}
}
describe("10. run length encoding of duplicate elements in a list") {
it("should return List of Nil for empty list") {
Nil.runLengthEncoding() shouldEqual Nil
}
it("should return List(List((1, 1))) for List(1)") {
List(1).runLengthEncoding() shouldEqual List((1, 1))
}
it("should return List((3, 1), (1, 2), (2, 3)) for List(1,1,1,2,3,3)") {
List(1, 1, 1, 2, 3, 3).runLengthEncoding() shouldEqual List((3, 1), (1, 2), (2, 3))
}
}
describe("11. modified run length encoding of duplicate elements in a list") {
it("should return Nil for empty list") {
Nil.runLengthEncodingModified() shouldEqual Nil
}
it("should return List(1) for List(1)") {
List(1).runLengthEncodingModified() shouldEqual List(1)
}
it("should return List((2, 1)) for List(1, 1)") {
List(1, 1).runLengthEncodingModified() shouldEqual List((2, 1))
}
it("should return List((2, 1), 3) for List(1, 1, 3)") {
List(1, 1, 3).runLengthEncodingModified() shouldEqual List((2, 1), 3)
}
it("should return List((3, 1), 2, (2, 3)) for List(1,1,1,2,3,3)") {
List(1, 1, 1, 2, 3, 3).runLengthEncodingModified() shouldEqual List((3, 1), 2, (2, 3))
}
}
describe("12. Decode a run-length encoded list") {
def decode[A](t: (Int, A)) = List.fill(t._1)(t._2)
it("should return List(2) for List((1, 2))") {
List((1, 2)).myFlatMap(decode) shouldEqual List(2)
}
it("should return List(2, 3, 4, 5) for List((1, 2), (2, 3), (2, 5))") {
List((1, 2), (2, 3), (2, 5)).myFlatMap(decode) shouldEqual List(2, 3, 3, 5, 5)
}
}
describe("13. direct run length encoding (without using pack method from previous example) of duplicate elements in a list") {
it("should return Nil for empty list") {
Nil.encodeDirect() shouldEqual Nil
}
it("should return List(List((1, 1))) for List(1)") {
List(1).encodeDirect() shouldEqual List((1, 1))
}
it("should return List((3, 1), (1, 2), (2, 3)) for List(1,1,1,2,3,3)") {
List(1, 1, 1, 2, 3, 3).encodeDirect() shouldEqual List((3, 1), (1, 2), (2, 3))
}
}
describe("14. duplicate the elements of a list") {
it("should return List(1, 1) for List(1)") {
List(1).duplicate shouldEqual List(1, 1)
}
it("should return List(1, 1, 3, 3) for List(1, 3)") {
List(1, 3).duplicate shouldEqual List(1, 1, 3, 3)
}
}
describe("15. duplicate the elements of a list given number of times") {
it("should return List(1, 1) for List(1) duplicated 2 times") {
List(1).duplicateN(2) shouldEqual List(1, 1)
}
it("should return List(1, 1, 1, 3, 3, 3) for List(1, 3) duplicated 3 times") {
List(1, 3).duplicateN(3) shouldEqual List(1, 1, 1, 3, 3, 3)
}
}
describe("16. Drop every Nth element from a list") {
it("should return List(1, 3, 5) for List(1, 2, 3, 4, 5, 6) after dropping every 2nd element") {
List(1, 2, 3, 4, 5, 6).dropN(2) shouldEqual List(1, 3, 5)
}
it("should return empty list for List(1, 2, 3, 4, 5, 6) after dropping every 1 element") {
List(1, 2, 3, 4, 5, 6).dropN(1) shouldEqual List()
}
}
describe("17. Split a list into two parts") {
it("should return (Nil, Nil) when splitting an empty list") {
Nil.mySplit(1) shouldEqual (Nil, Nil)
}
it("should return (List(1), Nil) when splitting List(1)") {
List(1).mySplit(1) shouldEqual (List(1), Nil)
}
it("should return (List(1), List(2)) when splitting List(1,2) at 1") {
List(1, 2).mySplit(1) shouldEqual (List(1), List(2))
}
it("should return (List(1, 2), Nil) when splitting List(1,2) at 2") {
List(1, 2).mySplit(2) shouldEqual (List(1, 2), Nil)
}
it("should return (Nil, List(1, 2)) when splitting List(1,2) at 0") {
List(1, 2).mySplit(0) shouldEqual (Nil, List(1, 2))
}
it("should return (List(1, 2), List(3,4,5)) when splitting List(1,2,3,4,5) at 2") {
List(1, 2, 3, 4, 5).mySplit(2) shouldEqual (List(1, 2), List(3,4,5))
}
}
describe("18. Extract a slice from a list") {
it("should return Nil when extracting slice from 0 to 0 in List(1)") {
List(1).mySlice(0, 0) shouldEqual Nil
}
it("should return List(1) when extracting slice from 0 to 1 in List(1)") {
List(1).mySlice(0, 1) shouldEqual List(1)
}
it("should return List(3, 4, 5) when extracting slice from 3 to 5 in List(0,1,2,3,4,5,6)") {
List(0,1,2,3,4,5,6).mySlice(3, 6) shouldEqual List(3,4,5)
}
}
describe("19. Rotate a list N places to the left") {
it("should rotate list by 3 places from beginning when n = 3") {
List(1,2,3,4,5,6,7,8,9,10).rotateLeft(3) shouldEqual List(4,5,6,7,8,9,10,1,2,3)
}
it("should rotate list by 3 places from end when n = -3") {
List(1,2,3,4,5,6,7,8,9,10).rotateLeft(-3) shouldEqual List(8,9,10,1,2,3,4,5,6,7)
}
}
describe("20. Remove the Kth element from a list") {
it("should remove 2nd element from the list") {
List(1,2,3,4).removeKthElement(1) shouldEqual (List(1,3,4), 2)
}
it("should remove last element from the list") {
List(1,2,3,4,5,6,7,8,9).removeKthElement(8) shouldEqual (List(1,2,3,4,5,6,7,8), 9)
}
it("should remove first element from the list") {
List(1,2,3).removeKthElement(0) shouldEqual (List(2,3), 1)
}
}
describe("21. Insert an element at a given position into a list") {
it("should insert element at 2nd position") {
List(1,2,3,4).insertAt(1, 5) shouldEqual List(1,5,2,3,4)
}
it("should insert element at starting of list") {
List(1,2,3,4).insertAt(0, 5) shouldEqual List(5,1,2,3,4)
}
it("should insert element at end of list") {
List(1,2,3,4).insertAt(4, 5) shouldEqual List(1,2,3,4,5)
}
}
describe("22. Create a list containing all integers within a given range.") {
it("should create List(4,5,6,7,8,9) from range 4 to 9") {
MyList.createListForRange(4, 9) shouldEqual List(4,5,6,7,8,9)
}
it("should create List(4,5,6,7,8,9) from range -4 to 4") {
MyList.createListForRange(-4, 4) shouldEqual List(-4,-3,-2,-1,0,1,2,3,4)
}
}
describe("23. Extract a given number of randomly selected elements from a list") {
it("should remove 3 elements randomly from a list of 8") {
List(1,2,3,4,5,6,7,8).randomDelete(3).size shouldEqual 3
}
it("should remove 3 elements randomly from a list of 3") {
List(1,2,3).randomDelete(3).size shouldEqual 3
}
}
describe("24. Lotto: Draw N different random numbers from the set 1..M") {
it("should extract 6 random elements from range 1 to 21") {
MyList.lotto(6, 21).size shouldEqual 6
}
}
describe("25. Generate a random permutation of the elements of a list") {
it("should remove 3 elements randomly from a list of 8") {
val input = List(1,2,3,4,5,6,7,8)
val output = input.randomPermutate()
output.toSet.subsetOf(input.toSet) shouldBe true
output shouldNot equal(input)
}
}
}
describe("My List method implementations") {
describe("take while") {
it("should return Nil for empty list") {
List().myTakeWhile(_ => true) shouldEqual Nil
}
it("should return 1 for List(1) when true") {
List(1).myTakeWhile(_ => true) shouldEqual List(1)
}
it("should return Nil for List(1) when false") {
List(1).myTakeWhile(_ => false) shouldEqual Nil
}
it("should return List(1) for List(1,2) when taking 1") {
List(1, 2).myTakeWhile(_ == 1) shouldEqual List(1)
}
it("should return List(1) for List(1,2,1) when taking 1") {
List(1, 2, 1).myTakeWhile(_ == 1) shouldEqual List(1)
}
it("should return List(1,1,1) for List(1,1,1,2,1,1) when taking 1") {
List(1, 1, 1, 2, 1, 1, 1).myTakeWhile(_ == 1) shouldEqual List(1, 1, 1)
}
}
describe("drop while") {
it("should return Nil for empty list") {
Nil.myDropWhile(_ => true) shouldEqual Nil
}
it("should return 1 for List(1) when false") {
List(1).myDropWhile(_ => false) shouldEqual List(1)
}
it("should return Nil for List(1) when true") {
List(1).myDropWhile(_ => true) shouldEqual Nil
}
it("should return List(2) for List(1,2) when taking 1") {
List(1, 2).myDropWhile(_ == 1) shouldEqual List(2)
}
it("should return List(2,1) for List(1,2,1) when taking 1") {
List(1, 2, 1).myDropWhile(_ == 1) shouldEqual List(2, 1)
}
it("should return List(2,1,1) for List(1,1,1,2,1,1) when taking 1") {
List(1, 1, 1, 2, 1, 1).myDropWhile(_ == 1) shouldEqual List(2, 1, 1)
}
}
describe("map") {
it("should transform empty list into empty") {
Nil.myMap(a => a) shouldEqual Nil
}
it("should transform List(2) into List(4) for double function") {
List(2).myMap(_ * 2) shouldEqual List(4)
}
it("should transform List(2,3) into List(4,6) for double function") {
List(2, 3).myMap(_ * 2) shouldEqual List(4, 6)
}
}
describe("flat map") {
it("should return Nil for List(Nil)") {
List(Nil).myFlatMap(a => a) shouldEqual Nil
}
it("should return List(1) for List(List(1))") {
List(List(1)).myFlatMap(a => a) shouldEqual List(1)
}
it("should return List(1, 1) for List(List(1, 1))") {
List(List(1, 1)).myFlatMap(a => a) shouldEqual List(1, 1)
}
it("should return List(1, 1) for List(List(1, 1), Nil)") {
List(List(1, 1), Nil).myFlatMap(a => a) shouldEqual List(1, 1)
}
it("should return List(1, 1, 2, 3, 4) for List(List(1, 1), List(2), List(3, 4))") {
List(List(1, 1), List(2), List(3, 4)).myFlatMap(a => a) shouldEqual List(1, 1, 2, 3, 4)
}
}
describe("grouped") {
it("should return Nil for Nil") {
Nil.myGrouped(1) shouldEqual List(Nil)
}
it("should return List(List(1)) for List(1) and group size as 1") {
List(1).myGrouped(1) shouldEqual List(List(1))
}
it("should return List(List(1), List(2)) for List(1, 2) and group size as 1") {
List(1, 2).myGrouped(1) shouldEqual List(List(1), List(2))
}
it("should return List(List(1)) for List(1) and group size as 3") {
List(1).myGrouped(3) shouldEqual List(List(1))
}
it("should return List(List(1, 2)) for List(1, 2) and group size as 2") {
List(1, 2).myGrouped(2) shouldEqual List(List(1, 2))
}
it("should return List(List(1, 2, 3), List(4)) for List(1, 2, 3, 4) and group size as 3") {
List(1, 2, 3, 4).myGrouped(3) shouldEqual List(List(1, 2, 3), List(4))
}
}
describe("filter") {
it("should return Nil for Nil when filter is satisfied") {
Nil.myFilter(f => true) shouldEqual Nil
}
it("should return correct when filter is satisfied") {
List(1, 2, 3).myFilter(_ > 1) shouldEqual List(2, 3)
}
}
describe("zip with index") {
it("should return Nil for empty list") {
Nil.myZipWithIndex shouldEqual Nil
}
it("should return zipped list for non-empty list") {
List(1, 2, 3).myZipWithIndex shouldEqual List((1, 0), (2, 1), (3, 2))
}
}
describe("take") {
it("should take 1 element from list of 3 when n = 1") {
List(1,2,3).myTake(1) shouldEqual List(1)
}
it("should take nothing from list of 3 when n = 0") {
List(1,2,3).myTake(0) shouldEqual Nil
}
it("should take nothing from list of 3 when n < 0") {
List(1,2,3).myTake(-1) shouldEqual Nil
}
it("should take all elements from list of 3 when n = 3") {
List(1,2,3).myTake(3) shouldEqual List(1, 2, 3)
}
it("should take all elements from list of 3 when n > 3") {
List(1,2,3).myTake(5) shouldEqual List(1, 2, 3)
}
}
describe("drop") {
it("should drop 1 element from list of 3 when n = 1") {
List(1,2,3).myDrop(1) shouldEqual List(2, 3)
}
it("should drop nothing from list of 3 when n = 0") {
List(1,2,3).myDrop(0) shouldEqual List(1,2,3)
}
it("should drop nothing from list of 3 when n < 0") {
List(1,2,3).myDrop(-1) shouldEqual List(1,2,3)
}
it("should drop all elements from list of 3 when n = 3") {
List(1,2,3).myDrop(3) shouldEqual Nil
}
it("should drop all elements from list of 3 when n > 3") {
List(1,2,3).myDrop(5) shouldEqual Nil
}
}
}
}
|
fc3df4276d489e66625453bb7fa4266dceb9bbc7
|
[
"Scala"
] | 3 |
Scala
|
singhalkul/s99
|
7a2c9192e245a15cd595b780be878d125f879c1c
|
5c324b207222013781ba1e906e6ee997eda588e4
|
refs/heads/master
|
<repo_name>Soochan/watch<file_sep>/clock.v
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 22:10:13 06/13/2015
// Design Name:
// Module Name: clock
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module clock(
input up,
input down,
input left,
input right,
input enter,
input esc,
input clk,
output [0:0] out,
output norm,
output [6:0] year,
output [6:0] month,
output [6:0] day
);
endmodule
<file_sep>/watch.v
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 20:42:38 06/01/2015
// Design Name:
// Module Name: watch
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module watch(
input up_i,
input down_i,
input left_i,
input right_i,
input enter_i,
input esc_i,
input clk,
output reg [7:0] o_m,
output reg [7:0] out [0:5],
output reg alarm
);
reg [3:0] mode;
reg up, down, left, right, enter, esc;
wire [6:0] norm;
wire [7:0] out_w [0:5], o_m_w;
wire [6:0] year, month, day, hour, min, sec;
wire [6:0] alarm_w;
always @(negedge clk) begin
up = ~up_i;
down = ~down_i;
left = ~left_i;
right = ~right_i;
enter = ~enter_i;
esc = ~esc_i;
end
date date_m(
.up(up),
.down(down),
.left(left),
.right(right),
.enter(enter),
.esc(esc),
.clk(clk),
.out(out_w[0]),
.norm(norm[0]),
.year(year),
.month(month),
.day(day)
);
clock clock_m(
.up(up),
.down(down),
.left(left),
.right(right),
.enter(enter),
.esc(esc),
.clk(clk),
.out(out_w[1]),
.norm(norm[1]),
.hour(hour),
.min(min),
.sec(sec)
);
alarm alarm_m(
.up(up),
.down(down),
.left(left),
.right(right),
.enter(enter),
.esc(esc),
.clk(clk),
.out(out_w[2]),
.alarm(alarm_w[2]),
.norm(norm[2]),
.hour(hour),
.min(min),
.sec(sec)
);
stopwatch stopwatch_m(
.up(up),
.down(down),
.left(left),
.right(right),
.enter(enter),
.esc(esc),
.clk(clk),
.out(out_w[3]),
.norm(norm[3])
);
timer timer_m(
.up(up),
.down(down),
.left(left),
.right(right),
.enter(enter),
.esc(esc),
.clk(clk),
.out(out_w[4]),
.norm(norm[4]),
.alarm(alarm_w[4])
);
d_day d_day_m(
.up(up),
.down(down),
.left(left),
.right(right),
.enter(enter),
.esc(esc),
.year(year),
.month(month),
.day(day),
.clk(clk),
.out(out_w[5]),
.norm(norm[5])
);
ladder ladder_m(
.up(up),
.down(down),
.left(left),
.right(right),
.enter(enter),
.esc(esc),
.clk(clk),
.out(out_w[6]),
.norm(norm[6])
);
endmodule
<file_sep>/blink.v
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 21:14:08 06/13/2015
// Design Name:
// Module Name: blink
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module blink(
input on,
input val,
input clk,
output out
);
reg [18:0] count;
initial begin
out = 0;
count = 0;
end
always @(posedge clk) begin
if (on & val) begin
count = count + 1;
if (count == 500000) begin
count = 0;
out = ~out;
end
end
else begin
out = val;
end
end
endmodule
|
f9e8ce9c8a0ab076666c8cbb82ee352bcdecab9e
|
[
"Verilog"
] | 3 |
Verilog
|
Soochan/watch
|
6bbef45c6d6092604b9f20e256bbd8d6905eb48e
|
ed29692d417cd617a65ef849ebb6ba5f87728488
|
refs/heads/master
|
<repo_name>DrMavenRebe/scrappy-scraper<file_sep>/src/main.py
#!/usr/bin/python2.7
__author__ = ('<NAME> <<EMAIL>>')
import csv
import scrapemark
import time
class Scraper():
"""
A collection of HTML scrapers. Use to pull trending links and best test
social APIs.
"""
# Grab the top 20 links from Digg's home page.
def scrape_digg(self):
urls = scrapemark.scrape("""
<body>
<div class='stories-container'>
{*
<div class="story-domain">
<a class="story-link" href='{{ [links] }}'></a>
</div>
*}
</div>
</body>
""",
url='http://digg.com/')['links']
return urls
# Grab 10 pages from the Topsy 100 list.
def scrape_topsy(self):
urls = scrapemark.scrape("""
<body>
<div class="list">
{*
<h3 class="title">
<a href='{{ [links].url }}'></a>
</h3>
*}
</div>
</body>
""",
url='http://topsy.com/top100')['links']
for page, offset in enumerate([15,30,45,60,75,90,105,120,135]):
urls += scrapemark.scrape("""
<body>
<div class="list">
{*
<h3 class="title">
<a href='{{ [links].url }}'></a>
</h3>
*}
</div>
</body>
""",
url='http://topsy.com/top100?offset='+str(offset)+'&om=f&page='+str(page+1)+'&thresh=top100')['links']
return urls
# Grab a total of 60 of the top most emailed, most bloged and viewed on the New York Times.
def scrape_nyt(self):
urls = scrapemark.scrape("""
<body>
{*
<div class='element2'>
<h3> <a href='{{ [links].url }}'></a> </h3>
</div>
*}
</body>
""",
url='http://www.nytimes.com/most-popular-emailed')['links']
urls += scrapemark.scrape("""
<body>
{*
<div class='element2'>
<h3> <a href='{{ [links] }}'></a> </h3>
</div>
*}
</body>
""",
url='http://www.nytimes.com/most-popular-viewed')['links']
urls += scrapemark.scrape("""
<body>
{*
<div class='element2'>
<h3> <a href='{{ [links] }}'></a> </h3>
</div>
*}
</body>
""",
url='http://www.nytimes.com/most-popular-blogged')['links']
return urls
# Write a scrapped file disk as a CSV.
def write_to_file(self, rows, filePath='../../data/'):
fileName = filePath + str(int(time.time())) + '.csv'
f = open(fileName, 'wb')
for row in rows:
f.write(str(row) + ',\n')
# Run all the scrapers and all the data to file accordingly.
# save: if True, save the files to disc respectfully.
# return the list
def scrape_all(self, save=True):
digg = self.scrape_digg()
print 'Found', len(digg), 'Digg items to file.'
topsy = self.scrape_topsy()
print 'Found', len(topsy), 'Topsy items to file.'
nyt = self.scrape_nyt()
print 'Found', len(nyt), 'New York Times items to file.'
if save:
self.write_to_file(digg, filePath='../data/scrapped/digg/')
self.write_to_file(topsy, filePath='../data/scrapped/topsy/')
self.write_to_file(nyt, filePath='../data/scrapped/nyt/')
return digg + topsy + nyt
if __name__ == '__main__':
s = Scraper()
s.scrape_all()
<file_sep>/README.md
scrappy-scraper
===============
Python to pull stuff off the web
### Install
Make sure you're using Python 2.7
> $ python --version
And the python [package manager](https://pypi.python.org/pypi/setuptools), easy_install
Install the scapper package in the eggs dir.
> $sudo easy_install [this package](http://arshaw.com/scrapemark/download/)
|
69380dd98fe313fc9126b6cf94b153f550bb3e40
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
DrMavenRebe/scrappy-scraper
|
bf1a54bd37427e3aa99eda13e20e2ddeaf986c80
|
3e2d0ed8c53193517f54841a04105a32e14ff6c4
|
refs/heads/master
|
<file_sep>import os
import time
import random
#Defining the board
board=[" "," "," "," "," "," "," "," "," ", " "]
def print_header():
print("You can choose between 1 and 9")
#define board function
def print_board():
print(" | | ")
print(" "+board[1]+" | "+board[2]+" |"+board[3]+" ")
print(" | | ")
print("---|---|---")
print(" | | ")
print(" "+board[4]+" | "+board[5]+" |"+board[6]+" ")
print(" | | ")
print("---|---|---")
print(" | | ")
print(" "+board[7]+" | "+board[8]+" |"+board[9]+" ")
print(" | | ")
while True:
os.system("clear")
print_header()
print_board()
choice=input("Please choose an empty space for X. ")
choice=int(choice)
#Check to see if the space is empty first
if board[choice]==" ":
board[choice]="X"
else:
print("Sorry that sace isn't empty")
#check for X win
if((board[1]=="X" and board[2]=="X" and board[3]=="X")or
(board[4]=="X" and board[5]=="X" and board[6]=="X")or
(board[7]=="X" and board[8]=="X" and board[9]=="X")or
(board[1]=="X" and board[5]=="X" and board[9]=="X")or
(board[3]=="X" and board[5]=="X" and board[7]=="X")or
(board[1]=="X" and board[4]=="X" and board[7]=="X")or
(board[2]=="X" and board[5]=="X" and board[8]=="X")or
(board[3]=="X" and board[6]=="X" and board[9]=="X")):
print("X won !! Congratulations")
os.system("clear")
print_header()
print_board()
break
os.system("clear")
print_header()
print_board()
choice=input("Please choose an empty space for O. ")
choice=int(choice)
#Check to see if the space is empty first
if board[choice]==" ":
board[choice]="O"
else:
print("Sorry that sace isn't empty")
#check for X win
if((board[1]=="O" and board[2]=="O" and board[3]=="O")or
(board[4]=="O" and board[5]=="O" and board[6]=="O")or
(board[7]=="O" and board[8]=="O" and board[9]=="O")or
(board[1]=="O" and board[5]=="O" and board[9]=="O")or
(board[3]=="O" and board[5]=="O" and board[7]=="O")or
(board[1]=="O" and board[4]=="O" and board[7]=="O")or
(board[2]=="O" and board[5]=="O" and board[8]=="O")or
(board[3]=="O" and board[6]=="O" and board[9]=="O")):
print("O won !! Congratulations")
os.system("clear")
print_header()
print_board()
break
<file_sep>This is my tic_tac_toe game project....This includes creating the tic_tac_toe board, ofcourse header and instructions to let players understand the game. And then creating players 1 and 2 as it includes only "X" and "O". And finally one player of those two will win the game at the end !
|
51167f62e94f222ea72142389f5c416e7ab22fcb
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
Sai-Sravya-Thumati/demo
|
6091dc81af70c62c351cd424f21758dea68e25e1
|
6b75693fa3084e1611ed23439ad58286e141dfbc
|
refs/heads/master
|
<file_sep><?php
namespace App\Form;
use App\Entity\Place;
use Doctrine\DBAL\Types\FloatType;
use Doctrine\DBAL\Types\TextType;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use function Sodium\add;
class PlaceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name',)
->add('adress',)
->add('longitude',NumberType::class ,[
'scale'=>5])
->add('latitude',NumberType::class ,[
'scale'=>5])
->add('city',EntityType::class,array(
'class'=>'App\Entity\City',
'query_builder'=>function (EntityRepository $er){
return $er->createQueryBuilder('c');
},
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['data_class'=>Place::class]);
}
}<file_sep>{% extends 'base.html.twig' %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/groups.css') }}">
<div class="grid-container ">
<div class="grid-x app-group">
{{ form_start(groupForm) }}
{{ form_rest(groupForm) }}
<input type="submit" class="button">
{{ form_end(groupForm) }}
</div>
{% endblock %}
{% block title %}
{% endblock %}
<file_sep>{% extends 'base.html.twig' %}
{% block title %} {{ parent() }} | Connexion{% endblock %}
{% block body %}
<video autoplay muted loop class="myVideo">
<source src="{{ asset('assets/vid/login-black.mp4') }}" type="video/mp4">
</video>
<div class="sign-in-form login-content">
<form method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div class="mb-3">
You are logged in as {{ app.user.username }}, <a href="{{ path('app_logout') }}">Déconnexion</a>
</div>
{% endif %}
<h1 class="h3 mb-3 font-weight-normal text-center">Connexion</h1>
<label for="inputUsername" class="sign-in-form-username">Pseudo</label>
<input type="text" class="sign-in-form-username" value="{{ last_username }}" name="username" id="inputUsername" class="form-control" required autofocus>
<label for="inputPassword" class="sign-in-form-password">Mot de Passe</label>
<input type="password" name="password" class="sign-in-form-password" id="inputPassword" class="form-control" required>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
<div class="checkbox mb-3">
<label>
<input type="checkbox" name="_remember_me"> Se souvenir de moi
</label>
</div>
<button class="btn btn-lg btn-primary sign-in-form-button" type="submit">
Connexion
</button>
</form>
<div>
<a href="{{ path('app_forgot_password_request') }}">Mot de passe oublié?</a>
</div>
</div>
{% endblock %}
<file_sep><?php
namespace App\Form;
use App\Entity\City;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CityType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name',TextType::class,[
'data'=>'Lyon',
'label'=>'Nom de la ville',
'help'=>'La ville doit avoir un nom'
])
->add('postcode',NumberType::class,[
'scale'=>0,
'data'=>69130,
'label'=>'Code Postal',
'invalid_message'=>'Le code postal doit comporter 5 chiffres'
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => City::class]);
}
}<file_sep><?php
namespace App\Controller;
use App\Entity\User;
use App\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\This;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserController extends AbstractController
{
#[Route('/profil', name: 'user_profile')]
public function index(): Response
{
return $this->render('user/profile.html.twig', [
'controller_name' => 'UserController',
]);
}
#[Route('/profil/modifier', name: 'user_profile_modify')]
public function modifyProfile(EntityManagerInterface $em, Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
{
$user = $this->getUser();
$userForm = $this->createForm(UserType::class, $user);
$userForm->handleRequest($request);
if ($userForm->isSubmitted() && $userForm->isValid()) {
if ($user->getPlainPassword() !== null) {
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$userForm->get('plainPassword')->getData()
)
);
}
/*
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$userForm->get('plainPassword')->getData()
)
);*/
$em->persist($user);
$em->flush();
$user->setImageFile(null);
$this->addFlash('success', 'Le profil a bien été modifié!');
return $this->redirectToRoute('user_profile', []);
}
return $this->render('user/modify.html.twig', ["userForm" => $userForm->createView()]);
}
/**
* @Route ("/profil/view/{id}", name="user_profile_view",requirements={"id"="\d+"})
* @param EntityManagerInterface $entityManager
* @param $id
* @return Response
*/
public function viewProfile(EntityManagerInterface $entityManager,$id): Response {
$user = $this->getUser();
$userRepo = $entityManager->getRepository(User::class);
$userProfile = $userRepo->find($id);
if($userProfile==null){
return $this->redirectToRoute('home');
}
if($user->getUsername()==$userProfile->getUsername()){
return $this->redirectToRoute('user_profile');
}
return $this->render('user/profileView.html.twig',[
'userProfile'=>$userProfile
]);
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\City;
use App\Entity\Group;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class GroupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name');
$editedObject = $builder->getData();
$builder->add('members',EntityType::class,array(
'class'=>'App\Entity\User',
'multiple'=>true,
'expanded'=>true,
'query_builder'=> function(EntityRepository $er) {
return $er->createQueryBuilder('u');
},
));
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => Group::class]);
}
}<file_sep>
<div class="cell small-3 fancy">
<a href="{{ path('group_add_members',{'id':g.id}) }}"><h1>{{ g.name }}</h1></a>
{% for p in g.members %}
<h4>{{ p }}</h4>
{% endfor %}
</div><file_sep>{% extends 'base.html.twig' %}
{% block title %}
{{ parent() }} | Page introuvable ou inexistante
{% endblock %}
{% block body %}
{% set name = '404' %}
{% set text = 'Cette page n\'existe pas ou est introuvable'%}
<link rel="stylesheet" href="{{ asset('assets/css/errorpage.css') }}">
{% include 'error/errorpage.html.twig' %}
{% endblock %}<file_sep><div class="cell medium-9 ">
<div class="tabs-content vertical" data-tabs-content="example-tabs">
{% for meeting in meetings %}
<div class="info-box tabs-panel app-meeting-information {% if j == 1 %} is-active {% endif %}"
id="meeting{{ meeting.id }}">
<div class="grid-container">
<div class="grid-x">
<h4 class="cell small-6">{{ meeting.name }} </h4> <h6 class="cell small-6"> Status
: {{ meeting.status }}</h6>
<div class="cell small-6">
<h4>
{{ meeting.place.name }}
</h4>
</div>
<span class="cell small-6">{{ meeting.place.adress }} a {{ meeting.place.city.name }}</span>
<div class="cell small-2">
<a href="https://www.google.com/maps/search/?api=1&query={{ meeting.place.latitude }},{{ meeting.place.longitude }}">
<span class="material-icons-outlined">
explore
</span>
</a>
<a href="https://www.google.com/search?q={{ meeting.place.name }} {{meeting.place.city}}">
<span class="material-icons-outlined">
pin_drop
</span>
</a>
</div>
<p class="cell small-10">{{ meeting.maxParticipants }} participants maximum , Début a {{ meeting.timeStarting |date("m/d/y - H:i") }} Durée : {{ meeting.length }} minutes
organisé par {{ meeting.organisedBy.firstName }}</p>
<p class="cell small-12">{{ meeting.information }}</p>
<h5 class="cell small-12">Date limite d'inscription : {{ meeting.registerUntil | date("m/d/y - H:i") }}</h5>
<p class="cell small-2"><button class="button" data-open="userList{{ meeting.id }}">Liste des participants</button></p>
<div class="reveal" id="userList{{ meeting.id }}" data-reveal>
<div class="grid-container">
<div class="grid-x grid-margin-x small-up-2 medium-up-3">
{% for p in meeting.participants %}
{% set var = asset('assets/img/profile_picture/') ~ p.imageName %}
<div class="cell">
<div class="card">
<img src="{{ var }}">
<div class="card-section">
<h4>
<a href="{{ path('user_profile_view' ,{'id':p.id }) }}">{{ p }}</a>
</h4>
<p>{{ p.firstName }} {{ p.lastName }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="cell small-12">
{% if (meeting.registerUntil > date() and meeting.status.label == 'Ouverte') or(meeting.status.label == 'Cloturee' and app.user in (meeting.participants)) %}
<button class="button success"><a href="{{ path('meeting_add_or_remove',{'id':meeting.id}) }}"><h5>Je veux m'inscrire !
/ Je veux me désister</h5></a></button>
{% else %}
<h5>
L'inscription est impossible a cet instant
</h5>
{% endif %}
{% if meeting.organisedBy.username == app.user.username and meeting.status.label != 'Annulee' %}
<p class="cell small-2">
<a href="{{ path('meeting_cancel',{'id':meeting.id}) }}">
<button class="alert button" data-toggle="animatedModal10">Annuler sortie</button>
</a>
</p>
{% endif %}
</div>
{# <div class="reveal" id="animatedModal10" data-reveal data-close-on-click="true"
data-animation-in="slide-in-down" data-animation-out="scale-out-down">
<h2>Are you sure?</h2>
<h4>Enter a reason for the cancellation</h4>
<a href="{{ path('meeting_cancel',{'id':meeting.id}) }}">
<button type="submit" class="button secondary app-meeting-filter">Cancel</button>
</a>
<button class="close-button" data-close aria-label="Close reveal" type="button">
<span aria-hidden="true">×</span>
</button>
</div> #}
</div>
</div>
</div>
{% set j = j + 1 %}
{% endfor %}
</div>
</div><file_sep>{% extends 'base.html.twig' %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/profile.css')}}">
{{ form_start(userForm) }}
<div class="grid-container app-modify-profile-box">
<div class="grid-x grid-padding-x align-center box-inner">
<h2 class="cell small-12">Modifier son profil</h2>
<div class="cell small-6">
{{ form_row(userForm.username) }}
</div>
<div class="cell small-6">
{{ form_row(userForm.firstName) }}
</div>
<div class="cell small-6">
{{ form_row(userForm.lastName) }}
</div>
<div class="cell small-6">
{{ form_row(userForm.email) }}
</div>
<div class="cell small-6">
{{ form_row(userForm.phone) }}
</div>
<div class="cell small-12">
{{ form_row(userForm.plainPassword) }}
</div>
{{ form_rest(userForm) }}
<button class="button" type="submit">Modifier !</button>
{{ form_end(userForm) }}
</div>
</div>
{% endblock %}
{% block title %}
{{ parent() }} | Modifier son profil
{% endblock %}
<file_sep>{% extends 'base.html.twig' %}
{% block title %}{{ parent() }} | Ajouter un lieu{% endblock %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/profile.css')}}">
<style>
.required{
color: white;
}
</style>
<video autoplay muted loop class="myVideo">
<source src="{{ asset('assets/vid/place.mp4') }}" type="video/mp4">
</video>
{{ form_start(placeForm) }}
<div class="grid-container app-modify-profile-box app-add-place">
<div class="grid-x grid-padding-x align-center box-inner">
<h2 class="cell small-12">Ajouter un lieu</h2>
<div class="cell small-6">
{{ form_row(placeForm.name) }}
</div>
<div class="cell small-12">
{{ form_row(placeForm.city) }}
</div>
<div class="cell small-6">
{{ form_row(placeForm.adress) }}
</div>
<div class="cell small-6">
{{ form_row(placeForm.longitude) }}
</div>
<div class="cell small-6">
{{ form_row(placeForm.latitude) }}
</div>
{{ form_rest(placeForm) }}
<button class="button" type="submit">Ajouter !</button>
{{ form_end(placeForm) }}
</div>
</div>
{% endblock %}
<file_sep><?php
namespace App\Controller\Admin;
use App\Entity\Campus;
use App\Entity\City;
use App\Entity\Group;
use App\Entity\Meeting;
use App\Entity\Place;
use App\Entity\State;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DashboardController extends AbstractDashboardController
{
/**
* @Route("/admin", name="admin_dashboard")
*/
public function index(): Response
{
return parent::index();
}
public function configureDashboard(): Dashboard
{
return Dashboard::new()
->setTitle('Meetup');
}
public function configureMenuItems(): iterable
{
return [MenuItem::linktoDashboard('Dashboard', 'fa fa-home'),
MenuItem::linkToCrud('User','fa fa-users',User::class ),
MenuItem::linkToCrud('Meeting','fa fa-handshake',Meeting::class) ,
MenuItem::linkToCrud('Place','fa fa-map-marker-alt',Place::class ),
MenuItem::linkToCrud('City','fa fa-city',City::class ),
MenuItem::linkToCrud('State','fa fa-info-circle',State::class ),
MenuItem::linkToCrud('Campus','fa fa-school',Campus::class ),
MenuItem::linkToCrud('Groups','fa fa-user-friends',Group::class ),
];
// yield MenuItem::linkToCrud('The Label', 'fas fa-list', EntityClass::class);
}
}
<file_sep><style type="text/css">
.header {
background: #8a8a8a;
}
.header .columns {
padding-bottom: 0;
}
.header p {
color: #fff;
margin-bottom: 0;
}
.header .wrapper-inner {
padding: 20px; /*controls the height of the header*/
}
.header .container {
background: #8a8a8a;
}
.wrapper.secondary {
background: #f3f3f3;
}
</style>
<!-- move the above styles into your custom stylesheet -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation-emails/2.3.1/foundation-emails.min.css" integrity="<KEY> crossorigin="anonymous" />
<container>
<spacer size="16"></spacer>
<row>
<columns>
<h1>Hi, {{ username }}</h1>
<p class="lead">{{ text }} </p>
</columns>
</row>
<wrapper class="secondary">
<spacer size="16"></spacer>
<row>
<columns small="12" large="6">
<h5>Connect With Us:</h5>
<menu class="vertical">
<a style="text-align: left;" href="https://twitter.com/Meetup">Twitter</a>
<a style="text-align: left;" href="https://www.facebook.com/Meetup">Facebook</a>
</menu>
</columns>
<columns small="12" large="6">
<h5>Contact Info:</h5>
<p>Phone: 408-341-0600</p>
<p>Email: <a href="mailto:<EMAIL>"><EMAIL></a></p>
</columns>
</row>
</wrapper>
</container><file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends AbstractController
{
#[Route('/',name: 'home')]
public function index(): Response {
return $this->render('default/index.html.twig');
}
/**
* @Route ("/home/theme/{id}", name="home_theme",requirements={"id"="\d+"})
*/
public function selectTheme($id): Response
{
$expire = 6 * 30 * 24 * 3600;
$cookie = Cookie::create('theme')
->withValue($id);
$this->addFlash('success', 'Choix du theme actif!');
$response = $this->redirectToRoute('home');
$response->headers->setCookie($cookie);
return $response;
}
/**
* @Route ("/home/langue/{id}", name="home_langue",requirements={"id"="\d+"})
*/
public function selectLangue($id): Response {
$expire = 6*30*24*3600;
$cookie = Cookie::create('langue')
->withValue($id)
->withExpires($expire)
->withDomain('.meetup.com')
->withSecure(true);
$this->addFlash('success', 'Choix de langue actif!');
return $this->render('default/index.html.twig');
}
}
<file_sep>{% extends 'base.html.twig' %}
{% block title %}{{ parent()}} | Accueil!{% endblock %}
{% block body %}
{% if not app.user %}
<div class="callout large alert">
<h5>Connectez vous gratuitement !</h5>
<p>Rejoignez une communaute grandissante et organisez vos evenements en toute facilité</p>
<a href="{{ path('app_login') }}">Connectez vous pour participer a la communauté</a>
</div>
{% endif %}
{# -------------------------------------- ORBIT PART -------------------------------------- #}
<div class="orbit hide-for-small-only" role="region" aria-label="Favorite Space Pictures" data-orbit data-options="animInFromLeft:fade-in; animInFromRight:fade-in; animOutToLeft:fade-out; animOutToRight:fade-out;">
<div class="orbit-wrapper">
<div class="orbit-controls">
<button class="orbit-previous"><span class="show-for-sr">Image Précédente</span>◀︎</button>
<button class="orbit-next"><span class="show-for-sr">Image Suivante</span>▶︎</button>
</div>
<ul class="orbit-container">
<li class="is-active orbit-slide">
<figure class="orbit-figure">
<img class="orbit-image app-bg-img" src="{{ asset('assets/img/bg/orange.jpg') }}" alt="Photo d'une soirée du 20/08/2019">
<figcaption class="orbit-caption">Soirée du 20/08/2019</figcaption>
<span class="hero-text">Organisez des rencontres inoubliables</span>
</figure>
</li>
<li class="orbit-slide">
<figure class="orbit-figure">
<img class="orbit-image app-bg-img" src="{{ asset('assets/img/bg/purple.jpg') }}" alt="Photo d'une soirée du 12/01/2019">
<figcaption class="orbit-caption">Soirée du 12/01/2019</figcaption>
<span class="hero-text">Vous vous souviendrez de ces soirées</span>
</figure>
</li>
</ul>
</div>
<nav class="orbit-bullets">
<button class="is-active" data-slide="0">
<span class="show-for-sr">Image de soirée.</span>
<span class="show-for-sr" data-slide-active-label>Image Actuelle</span>
</button>
<button data-slide="1"><span class="show-for-sr">Image de Soirée</span></button>
</nav>
</div>
<div class="show-for-small-only">
<div class="media-object stack-for-small">
<div class="media-object-section">
<div class="thumbnail">
<img src= "{{ asset('assets/img/bg/orange.jpg')}}">
</div>
</div>
<div class="media-object-section">
<h4>Soirée de 20/08/2019</h4>
<p>Organisez des rencontres inoubliables</p>
</div>
</div>
<div class="media-object stack-for-small">
<div class="media-object-section">
<div class="thumbnail ">
<img src= "{{ asset('assets/img/bg/purple.jpg')}}">
</div>
</div>
<div class="media-object-section">
<h4>Soirée du 12/01/2019</h4>
<p>Vous vous souviendrez de ces soirées</p>
</div>
</div>
</div>
{% endblock %}
<file_sep><?php
namespace App\DataFixtures;
use App\Entity\State;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class StateFixtures extends Fixture
{
public const FIRST_STATE = 'FIRST_STATE';
public function load(ObjectManager $manager)
{
$state = new State();
$state->setLabel('Créée');
$manager->persist($state);
$this->setReference('state_1',$state);
$state = new State();
$state->setLabel('Ouverte');
$manager->persist($state);
$this->setReference('state_2',$state);
$state = new State();
$state->setLabel('Cloturee');
$manager->persist($state);
$this->setReference('state_3',$state);
$state = new State();
$state->setLabel('Activite en cours');
$manager->persist($state);
$this->setReference('state_4',$state);
$state = new State();
$state->setLabel('Passee');
$manager->persist($state);
$this->setReference('state_5',$state);
$state = new State();
$state->setLabel('Annulee');
$manager->persist($state);
$this->setReference('state_6',$state);
$manager->flush();
$this->setReference(self::FIRST_STATE, $state);
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\MeetingRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use App\Listeners\TimeListener;
/**
* @ORM\Entity(repositoryClass=MeetingRepository::class)
* @ORM\EntityListeners({TimeListener::class})
*/
class Meeting
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @Assert\NotBlank(message="Please provide a valid name")
* @Assert\Length(min=8, max=255)
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
*
* @Assert\GreaterThanOrEqual("now")
* @ORM\Column(type="datetime")
*/
private $timeStarting;
/**
* @Assert\Positive()
* @ORM\Column(type="integer")
*/
private $length;
/**
* @Assert\GreaterThanOrEqual("now")
* @Assert\LessThanOrEqual(propertyPath="timeStarting")
* @ORM\Column(type="datetime")
*/
private $registerUntil;
/**
* @Assert\GreaterThanOrEqual(8)
* @Assert\LessThan(300)
* @ORM\Column(type="integer")
*/
private $maxParticipants;
/**
* @Assert\Length(min=10, max=255)
* @ORM\Column(type="string", length=255)
*/
private $information;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="organiserOf",cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $organisedBy;
/**
* @ORM\ManyToMany(targetEntity=User::class, mappedBy="meetings",cascade={"persist"})
*/
private $participants;
/**
* @ORM\ManyToOne(targetEntity=Campus::class, inversedBy="meetings",cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $campus;
/**
* @ORM\ManyToOne(targetEntity=State::class, inversedBy="meetings",cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $status;
/**
* @Assert\NotBlank()
* @ORM\ManyToOne(targetEntity=Place::class, inversedBy="meetings",cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $place;
public function __construct()
{
$this->participants = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getTimeStarting(): ?\DateTimeInterface
{
return $this->timeStarting;
}
public function setTimeStarting(\DateTimeInterface $timeStarting): self
{
$this->timeStarting = $timeStarting;
return $this;
}
public function getLength(): ? int
{
return $this->length;
}
public function setLength(int $length): self
{
$this->length = $length;
return $this;
}
public function getRegisterUntil(): ?\DateTimeInterface
{
return $this->registerUntil;
}
public function setRegisterUntil(\DateTimeInterface $registerUntil): self
{
$this->registerUntil = $registerUntil;
return $this;
}
public function getMaxParticipants(): ?int
{
return $this->maxParticipants;
}
public function setMaxParticipants(int $maxParticipants): self
{
$this->maxParticipants = $maxParticipants;
return $this;
}
public function getInformation(): ?string
{
return $this->information;
}
public function setInformation(string $information): self
{
$this->information = $information;
return $this;
}
public function getOrganisedBy(): ?User
{
return $this->organisedBy;
}
public function setOrganisedBy(?User $organisedBy): self
{
$this->organisedBy = $organisedBy;
return $this;
}
/**
* @return Collection|User[]
*/
public function getParticipants(): Collection
{
return $this->participants;
}
public function addParticipant(User $participant): self
{
if (!$this->participants->contains($participant)) {
$this->participants[] = $participant;
$participant->addMeeting($this);
}
return $this;
}
public function removeParticipant(User $participant): self
{
if ($this->participants->removeElement($participant)) {
$participant->removeMeeting($this);
}
return $this;
}
public function getCampus(): ?Campus
{
return $this->campus;
}
public function setCampus(?Campus $campus): self
{
$this->campus = $campus;
return $this;
}
public function getStatus(): ?State
{
return $this->status;
}
public function setStatus(?State $status): self
{
$this->status = $status;
return $this;
}
public function getPlace(): ?Place
{
return $this->place;
}
public function setPlace(?Place $place): self
{
$this->place = $place;
return $this;
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Meetup!{% endblock %}</title>
{% block stylesheets %}
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/css/foundation.min.css"/>
<link rel="stylesheet" href="{{ asset('assets/css/main.css') }}">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Crete+Round&family=Squada+One&display=swap"
rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined"
rel="stylesheet">
{% if app.request.cookies.has('theme')%}
{% set test = app.request.cookies.get('theme') %}
{% if test == 2 %}
<link rel="stylesheet" href="{{ asset('assets/css/dark.css') }}">
{% elseif test == 3 %}
<link rel="stylesheet" href="{{ asset('assets/css/lime.css') }}">
{% elseif test == 4 %}
<link rel="stylesheet" href="{{ asset('assets/css/red.css') }}">
{% endif %}
{% endif %}
{% endblock %}
{% block javascripts %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.5.0-rc.1/js/foundation.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/motion-ui@1.2.3/dist/motion-ui.min.css"/>
<script>
jQuery(document).ready(function ($) {
$(document).foundation();
});
</script> {% endblock %}
</head>
<header> {% include ('inc/nav.html.twig') %}
</header>
{% for label, messages in app.flashes %}
{% for message in messages %}
<div class="callout secondary {{ label }} flash flash-{{ label }}" data-closable="slide-out-right">
{{ message }}
<button class="close-button" aria-label="Dismiss alert" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endfor %}
<body>
{% block body %}{% endblock %}
</body>
</html>
<file_sep><?php
namespace App\Controller;
use App\Entity\Place;
use App\Form\PlaceType;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\This;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class PlaceController extends AbstractController
{
#[Route('/place', name: 'place')]
public function index(Request $request, EntityManagerInterface $em): Response
{
$place = new Place();
$placeForm = $this->createForm(PlaceType::class,$place);
$placeForm->handleRequest($request);
if($placeForm->isSubmitted() && $placeForm->isValid()){
$em->persist($place);
$em->flush();
$this->addFlash('success', 'Le lieu a bien été ajouté');
return $this->redirectToRoute('home');
}
return $this->render('place/index.html.twig', [
'placeForm' => $placeForm->createView(),
]);
}
}
<file_sep>{% extends 'base.html.twig' %}
{% block title %}
{{ parent() }} | Annuler une sortie
{% endblock %}
{% block body %}
<div class="grid-x app-cancel-page">
<div class="cell small-8">
<link rel="stylesheet" href="{{ asset('assets/css/cancel.css') }}">
{{ form_start(form) }}
{{ form_row(form.explanation) }}
<button class="button danger" type="submit">Annuler cette sortie</button>
{{ form_end(form) }}
</div>
</div>
{% endblock %}
<file_sep><?php
namespace App\Entity;
use App\Repository\GroupRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=GroupRepository::class)
* @ORM\Table(name="`group`")
*/
class Group
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\ManyToMany(targetEntity=User::class, inversedBy="groups",cascade={"persist"})
*/
private $members;
public function __construct()
{
$this->members = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return Collection|User[]
*/
public function getMembers(): Collection
{
return $this->members;
}
public function addMember(User $member): self
{
if (!$this->members->contains($member)) {
$this->members[] = $member;
}
return $this;
}
public function removeMember(User $member): self
{
$this->members->removeElement($member);
return $this;
}
}
<file_sep><?php
namespace App\Controller;
use App\Data\CancelData;
use App\Data\SearchData;
use App\Entity\Meeting;
use App\Entity\State;
use App\Form\CancelForm;
use App\Form\MeetingType;
use App\Form\SearchForm;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\This;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
class MeetingController extends AbstractController
{
#[Route('/meeting', name: 'meeting_index',)]
public function index(EntityManagerInterface $em, Request $request): Response
{
$user = $this->getUser();
$data = new SearchData();
$form = $this->createForm(SearchForm::class, $data);
$form->handleRequest($request);
$meetingRepo = $this->getDoctrine()->getRepository(Meeting::class);
$meetings = $meetingRepo->findActive($data, $user);
return $this->render('meeting/index.html.twig', [
'meetings' => $meetings,
'form' => $form->createView(),
]);
}
/**
* @Route ("/meeting/{id}", name="meeting_add_or_remove",requirements={"id"="\d+"})
*/
public function addOrRemoveParticipant(EntityManagerInterface $em, $id, Request $request)
{
$user = $this->getUser();
$meetingRepo = $this->getDoctrine()->getRepository(Meeting::class);
$meeting = $meetingRepo->find($id);
//la sortie existe ??
//verifier le max de participants et le status
if ($meeting->getParticipants()->contains($user)) {
if ($meeting->getStatus()->getLabel() == 'Ouverte') {
$meeting->removeParticipant($user);
$em->persist($meeting);
$em->flush();
$this->addFlash('success', 'You have successfully been removed from this meeting!');
return $this->redirectToRoute('meeting_index');
} else {
$this->addFlash('warning', 'You cannot remove yourself from this meeting at this time!');
return $this->redirectToRoute('meeting_index');
}
} else {
$meeting->addParticipant($user);
$em->persist($meeting);
$em->flush();
$this->addFlash('success', 'You have successfully been added to this meeting!');
return $this->redirectToRoute('meeting_index');
}
}
#[Route('/meeting/add', name: 'meeting_add')]
public function add(MailerInterface $mailer, EntityManagerInterface $em, Request $request): Response
{
$user = $this->getUser();
$statusRepo = $em->getRepository(State::class);
$status = $statusRepo->findOneBy(['label'=>'Créée']);
$campus = $user->getCampus();
$meeting = new Meeting();
$meetingForm = $this->createForm(MeetingType::class, $meeting);
$meetingForm->handleRequest($request);
if ($meetingForm->isSubmitted() && $meetingForm->isValid()) {
$meeting->setOrganisedBy($user);
$meeting->setCampus($user->getCampus());
$status->addMeeting($meeting);
$campus->addMeeting($meeting);
$em->persist($meeting);
$em->flush();
$this->addFlash('success', 'The meeting was sucessfully created !');
$user->sendEmail(
$mailer,
'Confirmation : La sortie '.$meeting->getName() .'a été créée',
'La sortie '.$meeting->getName(). ' est valide et a bien étée créée');
return $this->redirectToRoute('meeting_index', []);
}
return $this->render('meeting/add.html.twig', [
'meetingForm' => $meetingForm->createView(),
]);
}
/**
* @Route ("/meeting/cancel/{id}", name="meeting_cancel",requirements={"id"="\d+"})
*/
public function cancelMeeting(MailerInterface $mailer ,EntityManagerInterface $em, $id, Request $request)
{
$user = $this->getUser();
$data = new CancelData();
$cancelform = $this->createForm(CancelForm::class, $data);
$cancelform->handleRequest($request);
if ( $cancelform->isSubmitted() && $cancelform->isValid()) {
$statusRepo = $this->getDoctrine()->getRepository(State::class);
$cancelledStatus = $statusRepo->findOneBy(['label' => 'Annulee']);
$meetingRepo = $this->getDoctrine()->getRepository(Meeting::class);
$cancelledMeeting = $meetingRepo->find($id);
$message = $data->explanation;
if ($cancelledMeeting->getOrganisedBy()->getUsername()== $user->getUsername()) {
$cancelledMeeting->setStatus($cancelledStatus);
$cancelledMeeting->setInformation($message);
$em->persist($cancelledMeeting);
$em->flush();
$this->addFlash('success', 'You have successfully cancelled this meeting!');
foreach ($cancelledMeeting->getParticipants() as $participant){
$participant->sendEmail(
$mailer,
'Annulation : La sortie '.$cancelledMeeting->getName() .'a été annulée',
'La sortie '.$cancelledMeeting->getName(). ' a été annulée');
return $this->redirectToRoute('meeting_index', []);
}
return $this->redirectToRoute('home');
} else {
$this->addFlash('warning', 'The cancellation failed!');
return $this->render('default/index.html.twig');
}
}
return $this->render('meeting/deletepage.html.twig',[
'form'=>$cancelform->createView()
]);
}
}
<file_sep><?php
namespace App\Controller\Admin;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TelephoneField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
class UserCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return User::class;
}
public function configureCrud(Crud $crud): Crud
{
return $crud->setFormOptions(
['validation_groups' => ['new_user']],
['validation_groups' => ['edit_user']],
);
}
public function configureFields(string $pageName): iterable
{
return [
IdField::new('id')->hideOnForm(),
TextField::new('username'),
TextField::new('<PASSWORD>'),
TextField::new('firstName'),
TextField::new('lastName'),
TelephoneField::new('phone'),
EmailField::new('email'),
BooleanField::new('isActive'),
BooleanField::new('isAdmin'),
AssociationField::new('campus'),
];
}
}
<file_sep><div class="title-bar" data-responsive-toggle="example-animated-menu" data-hide-for="medium">
<button class="menu-icon" type="button" data-toggle></button>
<div class="title-bar-title">Menu</div>
</div>
<div class="top-bar" id="example-animated-menu" data-animate="hinge-in-from-top spin-out">
<div class="top-bar-left">
<ul class="dropdown menu" data-dropdown-menu>
<li class="menu-text">Meetup!</li>
<li><a href="{{ path('home') }}">Accueil <span class="material-icons-outlined">
cottage
</span></a></li>
{% if app.user %}
<li>
<a href="#">Profil <span class="material-icons-outlined">
person_pin
</span></a>
<ul class="menu vertical">
<li><a href="{{ path('user_profile') }}">Profile</a></li>
<li><a href="{{ path('user_profile_modify') }}">Modifier Profil</a></li>
</ul>
</li>
<li>
<a href="#">Sorties <span class="material-icons-outlined">
nightlife
</span></a>
<ul class="menu vertical">
<li><a href="{{ path('meeting_index') }}">Sorties <span class="material-icons-outlined">
menu_book
</span></a></li>
<li><a href="{{ path('meeting_add') }}">Ajouter une sortie <span class="material-icons-outlined">
east
</span></a></li>
</ul>
</li><li><a href="#">Groupes <span class="material-icons-outlined">
transfer_within_a_station
</span></a>
<ul class="menu vertical">
<li><a href="{{ path('group_index') }}">Groupes <span class="material-icons-outlined">
group_work
</span></a></li>
<li><a href="{{ path('group_add') }}">Créer un Groupe <span class="material-icons-outlined">
add
</span></a></li>
</ul>
</li>
<li><a href="{{ path('place') }}">Lieux <span class="material-icons-outlined">
store
</span></a></li>
<li><a href="{{ path('city') }}">Villes <span class="material-icons-outlined">
location_city
</span></a></li>
<li><a href="{{ path('app_logout') }}">Déconnexion <span class="material-icons-outlined">
logout
</span></a></li>
{% if is_granted("ROLE_ADMIN") %}
<li><a href="{{ path('admin_dashboard') }}">Admin <span class="material-icons-outlined">
badge
</span></a></li>
{% endif %}
{% else %}
<li><a href="{{ path('app_login') }}">Connexion<span class="material-icons-outlined">
login
</span></a></li>
{#
<li><a href="{{ path('app_register') }}">Register</a></li>
#}
{% endif %}
</ul>
</div>
<div class="top-bar-right">
<ul class="menu" data-dropdown-menu>
<li><button class="button secondary" data-open="themeModal">Theme</button></li>
<li><button class="button secondary" data-open="langueModal">Langue</button></li>
</ul>
</div>
<div class="reveal" id="themeModal" data-reveal>
<h1>THEME SELECTOR</h1>
<p class="lead">Choix du theme</p>
<div class="grid-container">
<div class="grid-x align-center">
<a class="button cell small-2" href="{{ path('home_theme' , {'id':1}) }}">Classique</a>
<a class="button cell small-2" href="{{ path('home_theme' , {'id':2}) }}">Fantaisie</a>
<a class="button cell small-2" href="{{ path('home_theme' , {'id':3}) }}">Moderne</a>
<a class="button cell small-2" href="{{ path('home_theme' , {'id':4}) }}">Gothique</a>
</div>
</div>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="reveal" id="langueModal" data-reveal>
<h1>Langue !</h1>
<p class="lead">Choix de la langue</p>
<p>I'm a cool paragraph that lives inside of an even cooler modal. Wins!</p>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
</div><file_sep>-- Script de création de la base de données SORTIES
-- type : SQL Server 2012
--
CREATE TABLE ETATS (
no_etat INTEGER NOT NULL,
libelle VARCHAR(30) NOT NULL
)
ALTER TABLE ETATS ADD constraint etats_pk PRIMARY KEY (no_etat)
CREATE TABLE INSCRIPTIONS (
date_inscription smalldatetime NOT NULL,
sorties_no_sortie INTEGER NOT NULL,
participants_no_participant INTEGER NOT NULL
)
ALTER TABLE INSCRIPTIONS ADD constraint inscriptions_pk PRIMARY KEY (SORTIES_no_sortie, PARTICIPANTS_no_participant)
CREATE TABLE LIEUX (
no_lieu INTEGER NOT NULL,
nom_lieu VARCHAR(30) NOT NULL,
rue VARCHAR(30),
latitude FLOAT,
longitude FLOAT,
villes_no_ville INTEGER NOT NULL,
)
ALTER TABLE LIEUX ADD constraint lieux_pk PRIMARY KEY (no_lieu)
CREATE TABLE PARTICIPANTS (
no_participant INTEGER NOT NULL,
pseudo VARCHAR(30) NOT NULL,
nom VARCHAR(30) NOT NULL,
prenom VARCHAR(30) NOT NULL,
telephone VARCHAR(15),
mail VARCHAR(20) NOT NULL,
mot_de_passe VARCHAR(20) NOT NULL,
administrateur bit NOT NULL,
actif bit NOT NULL,
campus_no_campus INTEGER NOT NULL
)
ALTER TABLE PARTICIPANTS ADD constraint participants_pk PRIMARY KEY (no_participant)
ALTER TABLE PARTICIPANTS add constraint participants_pseudo_uk unique (pseudo)
CREATE TABLE CAMPUS (
no_campus INTEGER NOT NULL,
nom_campus VARCHAR(30) NOT NULL
)
ALTER TABLE CAMPUS ADD constraint campus_pk PRIMARY KEY (no_campus)
CREATE TABLE SORTIES (
no_sortie INTEGER NOT NULL,
nom VARCHAR(30) NOT NULL,
datedebut smalldatetime NOT NULL,
duree INTEGER,
datecloture smalldatetime NOT NULL,
nbinscriptionsmax INTEGER NOT NULL,
descriptioninfos VARCHAR(500),
etatsortie INTEGER,
urlPhoto VARCHAR(250),
organisateur INTEGER NOT NULL,
lieux_no_lieu INTEGER NOT NULL,
etats_no_etat INTEGER NOT NULL
)
ALTER TABLE SORTIES ADD constraint sorties_pk PRIMARY KEY (no_sortie)
CREATE TABLE VILLES (
no_ville INTEGER NOT NULL,
nom_ville VARCHAR(30) NOT NULL,
code_postal VARCHAR(10) NOT NULL
)
ALTER TABLE VILLES ADD constraint villes_pk PRIMARY KEY (no_ville)
ALTER TABLE INSCRIPTIONS
ADD CONSTRAINT inscriptions_participants_fk FOREIGN KEY ( participants_no_participant )
REFERENCES participants ( no_participant )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE INSCRIPTIONS
ADD CONSTRAINT inscriptions_sorties_fk FOREIGN KEY ( sorties_no_sortie )
REFERENCES sorties ( no_sortie )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE LIEUX
ADD CONSTRAINT lieux_villes_fk FOREIGN KEY ( villes_no_ville )
REFERENCES villes ( no_ville )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE SORTIES
ADD CONSTRAINT sorties_etats_fk FOREIGN KEY ( etats_no_etat )
REFERENCES etats ( no_etat )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE SORTIES
ADD CONSTRAINT sorties_lieux_fk FOREIGN KEY ( lieux_no_lieu )
REFERENCES lieux ( no_lieu )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE SORTIES
ADD CONSTRAINT sorties_participants_fk FOREIGN KEY ( organisateur )
REFERENCES participants ( no_participant )
ON DELETE NO ACTION
ON UPDATE no action
<file_sep><?php
namespace App\Controller;
use App\Entity\Group;
use App\Form\GroupType;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\This;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class GroupController extends AbstractController
{
#[Route('/group', name: 'group_index')]
public function index(EntityManagerInterface $em): Response
{
$user = $this->getUser();
$groupsRepository = $em->getRepository(Group::class);
$groups = $groupsRepository->findByUserId($user->getId());
return $this->render('group/index.html.twig', [
'groups'=>$groups
]);
}
#[Route('/group/add', name: 'group_add')]
public function addGroup(EntityManagerInterface $em, Request $request){
$user = $this->getUser();
$group = new Group();
$groupForm = $this->createForm(GroupType::class,$group);
$groupForm->handleRequest($request);
if($groupForm->isSubmitted() && $groupForm->isValid()) {
$group->addMember($user);
$em->persist($group);
$em->flush();
$this->addFlash('success','Le groupe a bien été crée');
return $this->redirectToRoute('group_index');
}
return $this->render('group/add.html.twig',[
'groupForm' => $groupForm->createView(),
]);
}
/**
* @Route ("/group/{id}", name="group_add_members",requirements={"id"="\d+"})
*/
public function addMember($id) {
return $this->render('group/add_members.html.twig');
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\StateRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=StateRepository::class)
*/
class State
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=20)
*/
private $label;
/**
* @ORM\OneToMany(targetEntity=Meeting::class, mappedBy="status", orphanRemoval=true,cascade={"persist"})
*/
private $meetings;
public function __construct()
{
$this->meetings = new ArrayCollection();
}
/**
* @param mixed $id
*/
public function setId($id): void
{
$this->id = $id;
}
public function getId(): ?int
{
return $this->id;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
/**
* @return Collection|Meeting[]
*/
public function getMeetings(): Collection
{
return $this->meetings;
}
public function addMeeting(Meeting $meeting): self
{
if (!$this->meetings->contains($meeting)) {
$this->meetings[] = $meeting;
$meeting->setStatus($this);
}
return $this;
}
public function removeMeeting(Meeting $meeting): self
{
if ($this->meetings->removeElement($meeting)) {
// set the owning side to null (unless already changed)
if ($meeting->getStatus() === $this) {
$meeting->setStatus(null);
}
}
return $this;
}
public function __toString() {
return $this->label;
}
}
<file_sep>{% extends 'base.html.twig' %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/meetings.css') }}">
<h2>Create a meeting</h2>
<div class="show-for-small-only"><h3>Vous ne pouvez pas créer de sorties sur mobile. Veuillez utiliser une table ou
un ordinateur pour ces opérations</h3></div>
<div class="grid-container">
<div class="grid-x grid-padding-x align-center hide-for-small-only">
<div class="cell medium-0"> {{ form_start(meetingForm) }}</div>
<div class="cell medium-4"> {{ form_row(meetingForm.name) }} </div>
<div class="cell medium-4"> {{ form_row(meetingForm.maxParticipants) }} </div>
<div class="cell medium-4"> {{ form_row(meetingForm.length) }} </div>
<div class="cell medium-5"> {{ form_row(meetingForm.timeStarting) }} </div>
<div class="cell medium-5"> {{ form_row(meetingForm.registerUntil) }} </div>
<div class="cell medium-4"> {{ form_row(meetingForm.place) }} </div>
<div class="cell medium-4"> {{ form_row(meetingForm.information) }} </div>
{# {{ form_widget(meetingForm) }} #}
<button class="button" type="submit">Créez !</button>
{{ form_end(meetingForm) }}
</div>
</div>
{% endblock %}
{% block title %}
{{ parent() }} | Create a meeting
{% endblock %}
<file_sep><?php
namespace App\Entity;
use App\Repository\UserRepository;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"username"})
* @UniqueEntity(fields={"email"})
* @Vich\Uploadable()
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
*
* @Assert\NotBlank(message="Entrez un pseudo valide")
* @Assert\Length(min=5,max=40)
* @ORM\Column(type="string", length=180, unique=true)
*/
private $username;
private $roles;
/**
* @Assert\NotCompromisedPassword()
* @var string The hashed password
* @ORM\Column(type="string")
* @Assert\Length(min=7, groups={"registration,password"})
*/
private $password;
private $plainPassword;
// Pour ne pas avoir a modifier le mot de passe a chaque fois que l'utilisateur le modifie
public function setPlainPassword(string $plainPassword)
{
$this->plainPassword = $plainPassword;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function eraseCredentials()
{
$this->plainPassword = null;
}
/**
* @Assert\Length(min=5,max=50)
* @Assert\NotBlank()
* @ORM\Column(type="string", length=50)
*/
private $lastName;
/**
* @Assert\Length(min=5,max=50)
* @Assert\NotBlank()
* @ORM\Column(type="string", length=50)
*/
private $firstName;
/* 0123456789
01 23 45 67 89
01.23.45.67.89
0123 45.67.89
0033 123-456-789
+33-1.23.45.67.89
+33 - 123 456 789
+33(0) 123 456 789
+33 (0)123 45 67 89
+33 (0)1 2345-6789
+33(0) - 123456789
sont captes par ce regex
*/
/**
*
* @Assert\Regex(
* pattern="/^(?:(?:\+|00)33[\s.-]{0,3}(?:\(0\)[\s.-]{0,3})?|0)[1-9](?:(?:[\s.-]?\d{2}){4}|\d{2}(?:[\s.-]?\d{3}){2})$/",*
* )
* @ORM\Column(type="string", length=15)
*/
private $phone;
/**
* @Assert\Email(
* message = "The email '{{ value }}' is not a valid email."
* )
* @ORM\Column(type="string", length=255)
*/
private $email;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/**
* @ORM\OneToMany(targetEntity=Meeting::class, mappedBy="organisedBy", orphanRemoval=true,cascade={"persist"})
*/
private $organiserOf;
/**
* @ORM\ManyToMany(targetEntity=Meeting::class, inversedBy="participants")
*/
private $meetings;
/**
* @ORM\Column(type="boolean")
*/
private $isAdmin;
/**
* @ORM\ManyToOne(targetEntity=Campus::class, inversedBy="students")
* @ORM\JoinColumn(nullable=false)
*/
private $campus;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @var string|null
*/
private ?string $imageName;
/**
* @var File|null
* @Vich\UploadableField(mapping="profile_picture", fileNameProperty="imageName", size="imageSize")
*/
private ?File $imageFile = null;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private ?int $imageSize;
/**
* @ORM\Column(type="datetime", nullable=true)
* @var DateTimeInterface|null
*/
private ?DateTimeInterface $updatedAt;
/**
* @ORM\ManyToMany(targetEntity=Group::class, mappedBy="members",cascade={"persist"})
*/
private $groups;
public function __construct()
{
$this->organiserOf = new ArrayCollection();
$this->meetings = new ArrayCollection();
$this->groups = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
if ($this->getIsAdmin()) {
return ['ROLE_ADMIN'];
}
else return ['ROLE_USER'];
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* @see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(string $phone): self
{
$this->phone = $phone;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getIsActive(): ?bool
{
return $this->isActive;
}
public function setIsActive(bool $isActive): self
{
$this->isActive = $isActive;
return $this;
}
/**
* @return Collection|Meeting[]
*/
public function getOrganiserOf(): Collection
{
return $this->organiserOf;
}
public function addOrganiserOf(Meeting $organiserOf): self
{
if (!$this->organiserOf->contains($organiserOf)) {
$this->organiserOf[] = $organiserOf;
$organiserOf->setOrganisedBy($this);
}
return $this;
}
public function removeOrganiserOf(Meeting $organiserOf): self
{
if ($this->organiserOf->removeElement($organiserOf)) {
// set the owning side to null (unless already changed)
if ($organiserOf->getOrganisedBy() === $this) {
$organiserOf->setOrganisedBy(null);
}
}
return $this;
}
/**
* @return Collection|Meeting[]
*/
public function getMeetings(): Collection
{
return $this->meetings;
}
public function addMeeting(Meeting $meeting): self
{
if (!$this->meetings->contains($meeting)) {
$this->meetings[] = $meeting;
}
return $this;
}
public function removeMeeting(Meeting $meeting): self
{
$this->meetings->removeElement($meeting);
return $this;
}
public function getIsAdmin(): ?bool
{
return $this->isAdmin;
}
public function setIsAdmin(bool $isAdmin): self
{
$this->isAdmin = $isAdmin;
return $this;
}
public function getCampus(): ?Campus
{
return $this->campus;
}
public function setCampus(?Campus $campus): self
{
$this->campus = $campus;
return $this;
}
public function __toString() {
return $this->username;
}
public function getImageName(): ?string
{
if (null == $this->imageName){
return 'default.jpg';
} else
return $this->imageName;
}
public function setImageName(?string $imageName): self
{
$this->imageName = $imageName;
return $this;
}
public function getImageFile(): ?File
{
return $this->imageFile;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* @param File|UploadedFile|null $imageFile
*/
public function setImageFile(?File $imageFile = null): void
{
$this->imageFile = $imageFile;
if (null !== $imageFile) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getImageSize(): ?int
{
return $this->imageSize;
}
public function setImageSize(?int $imageSize): self
{
$this->imageSize = $imageSize;
return $this;
}
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(?DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
public function serialize()
{
$this->imageFile = base64_encode($this->imageFile);
}
public function unserialize($serialized)
{
$this->imageFile = base64_decode($this->imageFile);
}
/**
* @return Collection|Group[]
*/
public function getGroups(): Collection
{
return $this->groups;
}
public function addGroup(Group $group): self
{
if (!$this->groups->contains($group)) {
$this->groups[] = $group;
$group->addMember($this);
}
return $this;
}
public function removeGroup(Group $group): self
{
if ($this->groups->removeElement($group)) {
$group->removeMember($this);
}
return $this;
}
public function sendEmail(MailerInterface $mailer, string $subject,string $text) :void
{
$email = (new TemplatedEmail())
->from('<EMAIL>')
->to($this->getEmail())
->subject($subject)
->htmlTemplate('email/confirmation.html.twig')
->context([
'username' => $this->getUsername(),
'text' => $text,
]);
$mailer->send($email);
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\PlaceRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass=PlaceRepository::class)
*/
class Place
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @Assert\NotBlank()
* @Assert\Length(min=4, max=255)
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @Assert\NotBlank()
* @Assert\Length(min=4, max=255)
* @ORM\Column(type="string", length=255)
*/
private $adress;
/**
* @Assert\NotBlank()
* @Assert\Range(
* min = -90,
* max = 90,
* notInRangeMessage = "Latitude must be between -90 and 90",
* ) * @ORM\Column(type="integer")
*/
private $latitude;
/**
* @Assert\Range(
* min = -180,
* max = 180,
* notInRangeMessage = "Longitude must be between -180 and 180")
* * @ORM\Column(type="integer")
*/
private $longitude;
/**
* @ORM\OneToMany(targetEntity=Meeting::class, mappedBy="place", orphanRemoval=true,cascade={"persist"})
*/
private $meetings;
/**
* @ORM\ManyToOne(targetEntity=City::class, inversedBy="places",cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $city;
public function __construct()
{
$this->meetings = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getAdress(): ?string
{
return $this->adress;
}
public function setAdress(string $adress): self
{
$this->adress = $adress;
return $this;
}
public function getLatitude(): ?int
{
return $this->latitude;
}
public function setLatitude(int $latitude): self
{
$this->latitude = $latitude;
return $this;
}
public function getLongitude(): ?int
{
return $this->longitude;
}
public function setLongitude(int $longitude): self
{
$this->longitude = $longitude;
return $this;
}
/**
* @return Collection|Meeting[]
*/
public function getMeetings(): Collection
{
return $this->meetings;
}
public function addMeeting(Meeting $meeting): self
{
if (!$this->meetings->contains($meeting)) {
$this->meetings[] = $meeting;
$meeting->setPlace($this);
}
return $this;
}
public function removeMeeting(Meeting $meeting): self
{
if ($this->meetings->removeElement($meeting)) {
// set the owning side to null (unless already changed)
if ($meeting->getPlace() === $this) {
$meeting->setPlace(null);
}
}
return $this;
}
public function getCity(): ?City
{
return $this->city;
}
public function setCity(?City $city): self
{
$this->city = $city;
return $this;
}
public function __toString() {
return $this->name;
}
}
<file_sep>{% extends 'base.html.twig' %}
{% block title %}{{ parent() }} Mot de pass oublié{% endblock %}
{% block body %}
<video autoplay muted loop class="myVideo">
<source src="{{ asset('assets/vid/login-black.mp4') }}" type="video/mp4">
</video>
{% for flashError in app.flashes('reset_password_error') %}
<div class="alert alert-danger" role="alert">{{ flashError }}</div>
{% endfor %}
<div class="request-content">
<h1>Mot de pass oublié</h1>
{{ form_start(requestForm) }}
{{ form_row(requestForm.email) }}
<div>
<small>
Entrez votre adress email et un lien sera envoyé pour choisir un nouveau mot de passe
</small>
</div>
<button class="button">Envoyer email</button>
{{ form_end(requestForm) }}</div>
{% endblock %}<file_sep>{% extends 'base.html.twig' %}
{% block title %}{{ parent() }} | Ajouter une ville{% endblock %}
{% block body %}
<style>
.required{
color: white;
}
</style>
<link rel="stylesheet" href="{{ asset('assets/css/profile.css')}}">
<video autoplay muted loop class="myVideo">
<source src="{{ asset('assets/vid/city.mp4') }}" type="video/mp4">
</video>
{{ form_start(cityForm) }}
<div class="grid-container app-modify-profile-box app-add-place">
<div class="grid-x grid-padding-x align-center box-inner">
<h2 class="cell small-12">Ajouter une ville</h2>
<div class="cell small-6">
{{ form_row(cityForm.name, { 'attr' : {'class':'testblanc'}}) }}
</div>
<div class="cell small-12">
{{ form_row(cityForm.postcode) }}
{{ form_rest(cityForm) }}
<button class="button" type="submit">Ajouter !</button>
</div>
{{ form_end(cityForm) }}
</div>
</div>
{% endblock %}
<file_sep><?php
namespace App\Data;
use App\Entity\Meeting;
class CancelData{
public ?string $explanation;
}<file_sep><?php
namespace App\DataFixtures;
use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserFixtures extends Fixture implements DependentFixtureInterface
{
private $passwordEncoder;
public const FIRST_USER = 'user_admin';
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public function load(ObjectManager $manager)
{
$faker = Factory::create('fr_FR');
$user = new User();
$user->setUsername('User');
$user->setFirstName('Valentin');
$user->setLastName('Trouillet');
$user->setEmail('<EMAIL>');
$user->setPhone('0478651423');
$user->setIsAdmin(true);
$user->setIsActive(true);
$user->setCampus($this->getReference('campus_'.mt_rand(1,10)));
$user->setPassword($this->passwordEncoder->encodePassword(
$user,
'<PASSWORD>'
));
$manager->persist($user);
$this->setReference('user_admin',$user);
for ($i = 1; $i <= 30; $i++) {
$user = new User();
$user->setUsername($faker->userName);
$user->setFirstName($faker->firstName());
$user->setLastName($faker->lastName);
$user->setEmail($faker->email);
$user->setPhone($faker->phoneNumber);
$user->setIsActive(true);
$user->setIsAdmin(false);
$user->setCampus($this->getReference('campus_'.mt_rand(1,10)));
$user->setPassword($this->passwordEncoder->encodePassword(
$user,
'tototo'
));
$manager->persist($user);
$this->setReference('user_'.$i,$user);
}
$manager->flush();
}
public function getDependencies()
{
return [CampusFixtures::class];
}
}
<file_sep>{% extends 'base.html.twig' %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/profile.css')}}">
<div class="grid-x grid-padding-x align-center profile-body profile-display">
{% include('user/profile-card-view.html.twig') %}
</div>
{#
<h3>{{ userProfile.username }}</h3>
<ul>
<li>First Name :{{ userProfile.firstName }}</li>
<li>Last Name :{{ userProfile.lastName }}</li>
<li>Phone : {{ userProfile.phone }}</li>
<li>Email :{{ userProfile.email }}</li>
<li>Campus :{{ userProfile.campus }}</li>
<img src="{{ asset('assets/img/profile_picture/') }}{{ userProfile.imageName }}" width="300px" alt="">
</ul> #}
{% endblock %}
{% block title %}
{{ parent() }} | {{ userProfile.username }}
{% endblock %}
<file_sep><?php
namespace App\Listeners;
use App\Entity\Meeting;
use App\Entity\State;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Event\LifecycleEventArgs;
class TimeListener
{
/*
* Trop de requetes : la solution serait de refaire une requete dans le controller et faire des reaquetes sql selon statut et l'heure actuelle.
public function postLoad(Meeting $meeting, LifecycleEventArgs $eventArgs)
{
$em = $eventArgs->getEntityManager();
$statusRepo = $eventArgs->getEntityManager()->getRepository(State::class);
// $ouverte = $statusRepo->findOneBy(['label' => 'Ouverte']);
// $cloturee = $statusRepo->findOneBy(['label' => 'Cloturee']);
// $enCours = $statusRepo->findOneBy(['label' => ' Activite en cours ']);
// $Passee = $statusRepo->findOneBy(['label' => 'Passee']);
// $cancelled = $statusRepo->findOneBy(['label'=>'Annulee']);
$ouverte = $statusRepo->find(97);
$cloturee = $statusRepo->find(98);
$enCours = $statusRepo->find(99);
$Passee = $statusRepo->find(100);
$cancelled = $statusRepo->find(101);
$meetingRepo = $eventArgs->getEntityManager()->getRepository(Meeting::class);
// $meetings = $meetingRepo->findAll();
$meetings = $meetingRepo->findALlnoParameters();
foreach ($meetings as $m) {
$start = $m->getTimeStarting();
$limit = $m->getRegisterUntil();
$max = $m->getMaxParticipants();
$nbParticipants = $m->getParticipants()->count();
$duration = $m->getLength();
//$timeFinished = $start;
//$timeFinished = $timeFinished->modify('+' . $duration . ' minutes');
$currentTime = new \DateTime();
//FIARE DES REQUETES AVEC status= x et current temps donc 5 requetes au lieu de tout ca !!!
if($m->getStatus() != $cancelled){
if ($limit >= $currentTime) {
$m->setStatus($ouverte);
}
if ($limit >= $currentTime && $max==$nbParticipants) {
$m->setStatus($cloturee);
}
if ($limit <= $currentTime) {
$m->setStatus($cloturee);
}
if ($start <= $currentTime) {
$m->setStatus($enCours);
}
$currentTime = $currentTime->modify('-' . $duration . ' minutes');
if ($start <= $currentTime) {
$m->setStatus($Passee);
}
}
$em->persist($m);
$em->flush();
}
}
*/
}<file_sep><?php
namespace App\Data;
use App\Entity\Campus;
class SearchData
{
public ?string $q = '';
public ?Campus $campus;
public ?\DateTime $max;
public ?\DateTime $min;
public ?bool $isOrganizedBy;
public ?bool $isRegisteredTo;
public ?bool $isNotRegisteredTo;
public ?bool $isOver;
}<file_sep>{% extends 'base.html.twig' %}
{% block title %}
{{ parent() }} | Accès non autorisé
{% endblock %}
{% block body %}
{% set name = '403' %}
{% set text = 'Vous n\'avez pas accès a cette page'%}
<link rel="stylesheet" href="{{ asset('assets/css/errorpage.css') }}">
{% include 'error/errorpage.html.twig' %}
{% endblock %}<file_sep><?php
namespace App\DataFixtures;
use App\Entity\Campus;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
class CampusFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
$faker = Factory::create('fr_FR');
for ($i=1;$i<=10;$i++){
$campus = new Campus();
$name = 'Ecole ' . $faker->lastName .' '. $faker->lastName;
$campus->setName($name);
$manager->persist($campus);
$this->setReference('campus_'.$i,$campus);
}
$manager->flush();
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\CampusRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=CampusRepository::class)
*/
class Campus
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\OneToMany(targetEntity=User::class, mappedBy="campus", orphanRemoval=true,cascade={"persist"})
*/
private $students;
/**
* @ORM\OneToMany(targetEntity=Meeting::class, mappedBy="campus", orphanRemoval=true,cascade={"persist"})
*/
private $meetings;
public function __construct()
{
$this->students = new ArrayCollection();
$this->meetings = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return Collection|User[]
*/
public function getStudents(): Collection
{
return $this->students;
}
public function addStudent(User $student): self
{
if (!$this->students->contains($student)) {
$this->students[] = $student;
$student->setCampus($this);
}
return $this;
}
public function removeStudent(User $student): self
{
if ($this->students->removeElement($student)) {
// set the owning side to null (unless already changed)
if ($student->getCampus() === $this) {
$student->setCampus(null);
}
}
return $this;
}
/**
* @return Collection|Meeting[]
*/
public function getMeetings(): Collection
{
return $this->meetings;
}
public function addMeeting(Meeting $meeting): self
{
if (!$this->meetings->contains($meeting)) {
$this->meetings[] = $meeting;
$meeting->setCampus($this);
}
return $this;
}
public function removeMeeting(Meeting $meeting): self
{
if ($this->meetings->removeElement($meeting)) {
// set the owning side to null (unless already changed)
if ($meeting->getCampus() === $this) {
$meeting->setCampus(null);
}
}
return $this;
}
public function __toString() {
return $this->name;
}
}
<file_sep><div class="moon"></div>
<div class="moon__crater moon__crater1"></div>
<div class="moon__crater moon__crater2"></div>
<div class="moon__crater moon__crater3"></div>
<div class="star star1"></div>
<div class="star star2"></div>
<div class="star star3"></div>
<div class="star star4"></div>
<div class="star star5"></div>
<div class="error">
<div class="error__title">{{ name }}</div>
<div class="error__subtitle">Hmmm...</div>
<div class="error__description">{{ text }}</div>
<a href="{{ path('home') }}"><button class="error__button error__button--active">ACCUEIL</button></a>
<a href="mailto:<EMAIL>"><button class="error__button">CONTACT</button></a>
</div>
<div class="astronaut">
<div class="astronaut__backpack"></div>
<div class="astronaut__body"></div>
<div class="astronaut__body__chest"></div>
<div class="astronaut__arm-left1"></div>
<div class="astronaut__arm-left2"></div>
<div class="astronaut__arm-right1"></div>
<div class="astronaut__arm-right2"></div>
<div class="astronaut__arm-thumb-left"></div>
<div class="astronaut__arm-thumb-right"></div>
<div class="astronaut__leg-left"></div>
<div class="astronaut__leg-right"></div>
<div class="astronaut__foot-left"></div>
<div class="astronaut__foot-right"></div>
<div class="astronaut__wrist-left"></div>
<div class="astronaut__wrist-right"></div>
<div class="astronaut__cord">
<canvas id="cord" height="500px" width="500px"></canvas>
</div>
<div class="astronaut__head">
<canvas id="visor" width="60px" height="60px"></canvas>
<div class="astronaut__head-visor-flare1"></div>
<div class="astronaut__head-visor-flare2"></div>
</div>
</div>
<script src="{{ asset('assets/js/error404.js') }}">
</script><file_sep>{% extends 'base.html.twig' %}
{% block title %}Hello GroupController!{% endblock %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/groups.css') }}">
<div class="grid-container ">
<div class="grid-x app-group">
{% for g in groups %}
{% include 'group/card.html.twig' %}
{% endfor %}
</div>
</div>
{% endblock %}
<file_sep><aside class="profile-card">
<header>
<!-- here’s the avatar -->
<img src="{{ asset('assets/img/profile_picture/') }}{{ app.user.imageName }}" alt="profile-picture">
<!-- Full Name -->
<h1>{{ app.user.firstName }} {{ app.user.lastName }}</h1>
<!-- Username -->
<h2>- {{ app.user.username }} -</h2>
</header>
<div class="profile-bio grid-y" style="height: 50%;">
<div class="cell small-3 ">
<h4>{{ app.user.email }}</h4>
</div>
<div class="cell small-3 ">
<h5>Phone : {{ app.user.phone }}</h5>
</div>
<div class="cell small-3 ">
<h4>{{ app.user.campus }}</h4>
</div>
</div>
</aside>
<file_sep>{% extends 'base.html.twig' %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/profile.css') }}">
<div class="grid-x grid-padding-x align-center profile-body profile-display">
{% include('user/profile-card.html.twig') %}
</div>
{% endblock %}
{% block title %}
{% endblock %}
<file_sep><?php
namespace App\Form;
use App\Entity\Meeting;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class MeetingType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name',TextType::class,[
'data'=>'Soirée au Bar-a-Go-Go',
'help' => 'Le nom de la sortie',
'label'=>'Nom',
])
->add('timeStarting', DateTimeType::class,[
'years'=>[2021,2022],
'label'=>'Debut de la soirée',
])
->add('length',ChoiceType::class,[
'choices' => [
'30 minutes' => 30,
'1 Heure' => 60,
'1 Heure & 30 minutes' => 90,
'2 heures' => 120,
'2 heures & 30 minutes' => 150,
'3 heures' => 180,
'3 heures & 30 minutes' => 210,
'4 heures' => 240,
'4 heures & 30 minutes' => 270,
'5 heures' => 300,
'5 heures & 30 minutes' => 330,
'6 heures' => 360,
'6 heures & 30 minutes' => 390,
'7 heures' => 420,
'7 heures & 30 minutes' => 450,
'8 heures' => 480,
'8 heures & 30 minutes' => 510,
'9 heures' => 540,
'9 heures & 30 minutes' => 570,
'10 heures' => 600,
],
'label' => 'Durée',
])
->add('maxParticipants',NumberType::class,[
'data' => 10,
'scale' => 0,
'label'=>'Participants maximum',
'invalid_message'=>'Nombre de participants maximum entre 8 et 300'
])
->add('information',TextType::class,[
'help'=>'Résumé de la sortie',
'invalid_message'=>'Au minimum 10 caractères'
])
->add('registerUntil',DateTimeType::class,[
'years'=>[2021,2022],
'label'=>'Date limite d\'inscription',
])
->add('place',EntityType::class,array(
'class'=>'App\Entity\Place',
'label'=>'Lieu',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('c');
},
));
// ->add('place',PlaceType::class);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => Meeting::class]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\City;
use App\Form\CityType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class CityController extends AbstractController
{
#[Route('/city', name: 'city')]
public function index(Request $request, EntityManagerInterface $em): Response
{
$city = new City();
$cityForm = $this->createForm(CityType::class,$city);
$cityForm->handleRequest($request);
if ($cityForm->isSubmitted() && $cityForm->isValid()) {
$cityRepo = $em->getRepository(City::class);
$em->persist($city);
$em->flush();
$this->addFlash('success', 'La ville a bien été ajoutée');
return $this->redirectToRoute('home');
}
return $this->render('city/index.html.twig', [
'cityForm' => $cityForm->createView(),
]);
}
}
<file_sep>{% extends 'base.html.twig' %}
{% block title %}{{ parent()}} Email envoyé{% endblock %}
{% block body %}
<video autoplay muted loop class="myVideo">
<source src="{{ asset('assets/vid/login-black.mp4') }}" type="video/mp4">
</video>
<div class="request-content">
<p>
Un email a été envoyé avec un lien pour réinitialiser votre mot de passe
Ce lien expirera dans {{ resetToken.expirationMessageKey|trans(resetToken.expirationMessageData, 'ResetPasswordBundle') }}.
</p>
<p>Si aucun email n'est reçu, vérifiez les pourriels ou <a href="{{ path('app_forgot_password_request') }}">réessayez</a>.</p>
</div>
{% endblock %}
<file_sep><?php
namespace App\Form;
use App\Data\SearchData;
use App\Entity\Campus;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class SearchForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('q',TextType::class,[
'label'=>false,
'required'=>false,
'attr'=>[
'placeholder'=>'Rechercher'
]
])
->add('campus',EntityType::class,[
'label'=>false,
'required'=>false,
'class'=>Campus::class,
])
->add('min', DateType::class,[
'label'=>false,
'required'=>false,
'years'=>[2021,2022],
'widget'=>'single_text',
'attr'=>[
'placeholder'=>'Entre '
]
])
->add('max', DateType::class,[
'label'=>false,
'required'=>false,
'years'=>[2021,2022],
'attr'=>[
'placeholder'=>'et '
]
])
->add('isOrganizedBy', CheckboxType::class,[
'label'=>false,
'required'=>false,
])
->add('isRegisteredTo', CheckboxType::class,[
'label'=>false,
'required'=>false,
])
->add('isNotRegisteredTo', CheckboxType::class,[
'label'=>false,
'required'=>false,
])
->add('isOver', CheckboxType::class,[
'label'=>false,
'required'=>false,
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['data_class'=>SearchData::class,
'method'=>'GET',
'csrf_protection'=>false
]);
}
public function getBlockPrefix()
{
return '';
}
}<file_sep><?php
namespace App\DataFixtures;
use App\Entity\Place;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
class PlaceFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager)
{
$faker = Factory::create('fr_FR');
for ($i=1;$i<=40;$i++){
$place = new Place();
$name = $faker->company.$faker->streetName;
$address = $faker->streetAddress;
$long = $faker->longitude;
$lat = $faker->latitude;
$cityName = 'City'.mt_rand(0,20);
$city = $this->getReference('city_'.mt_rand(1,20));
$place->setName($name)
->setAdress($address)
->setLatitude($lat)
->setLongitude($long)
->setCity($city);
$manager->persist($place);
$this->setReference('place_'.$i,$place);
}
$manager->flush();
}
public function getDependencies()
{
return [CityFixtures::class];
}
}
<file_sep>{{ form_start(form) }}
{{ form_row(form.q) }}
<h4>Campus</h4>
{{ form_row(form.campus) }}
<div class="container grid-x grid-margin-x ">
<h4 class="cell small-6">Date Minimum</h4> <h4 class="cell small-6">Date Maximum</h4>
</div>
<div class="container grid-x grid-margin-x">
<div class="cell small-6"> {{ form_row(form.min) }}</div>
<div class="cell small-6"> {{ form_row(form.max) }}</div>
</div>
<div class="container grid-x grid-margin-x ">
<div class="cell small-6 medium-3 switch app-meeting-checkboxes ">
<p class="checkbox-text-meeting">Sorties organisées</p>
{{ form_row(form.isOrganizedBy,{'attr':{'class': 'switch-input','label_attr': 'switch-paddle'}}) }}
</div>
<div class="cell small-6 medium-3 switch app-meeting-checkboxes">
<p class="checkbox-text-meeting">Sorties participées</p>
{{ form_row(form.isRegisteredTo,{'attr':{'class': 'switch-input','label_attr': 'switch-paddle'}}) }}
</div>
<div class="cell small-6 medium-3 switch app-meeting-checkboxes">
<p class="checkbox-text-meeting">Sorties non participées</p>
{{ form_row(form.isNotRegisteredTo,{'attr':{'class': 'switch-input','label_attr': 'switch-paddle'}}) }}
</div>
<div class="cell small-6 medium-3 switch app-meeting-checkboxes">
<p class="checkbox-text-meeting">Sorties antérieures</p>
{{ form_row(form.isOver,{'attr':{'class': 'switch-input','label_attr': 'switch-paddle'}}) }}
</div>
</div>
<button type="submit" class="button secondary app-meeting-filter">Filtrer</button>
{{ form_end(form) }}<file_sep># Meetup
A website to organize meetings and get-togethers
<file_sep><div class="cell medium-12 grid-container fluid">
<ul class="vertical tabs cell grid-x app-meeting-choice" data-tabs id="example-tabs"
data-deep-link="true" data-update-history="true" data-deep-link-smudge="true" data-deep-link-smudge-delay="500"
>
{% for meeting in meetings %}
<div class="tabs-title cell small-6 medium-3 {% if i == 1 %}is-active {% endif %}">
<a href="#meeting{{ meeting.id }}"><h4> {{ meeting.name }}</h4><h2>{{ meeting.participants |length }} / {{ meeting.maxparticipants }}</h2></a>
<p class="app-meeting-list-subtitle">Le {{ meeting.timeStarting | date("m/d/Y") }}
a {{ meeting.place.name }}, {{ meeting.place.city.name }}
<br>
Organisé par {{ meeting.organisedBy }} du campus {{ meeting.campus }}</p>
</div>
{% set i = i + 1 %}
{% endfor %}
</ul>
{# <div>{{ knp_pagination_render(meetings) }}</div> #}
</div><file_sep>{% extends 'base.html.twig' %}
{% block title %}{{ parent() }} | Liste des sorties{% endblock %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/meetings.css') }}">
{% if app.request.cookies.has('theme')%}
{% set test = app.request.cookies.get('theme') %}
{% if test == 2 %}
<link rel="stylesheet" href="{{ asset('assets/css/dark-meetings.css') }}">
{% elseif test == 3 %}
<link rel="stylesheet" href="{{ asset('assets/css/lime-meetings.css') }}">
{% elseif test == 4 %}
<link rel="stylesheet" href="{{ asset('assets/css/red-meetings.css') }}">
{% endif %}
{% endif %}
{% set i = 1 %}
{% set j = 1 %}
<div class="grid-container fluid app-meeting-list">
<div class="grid-x grid-margin-x">
<fieldset class="cell small-12 medium-3 filter-box">
{% include 'meeting/filter.html.twig' with {form: form} only %}
</fieldset>
{% include 'meeting/detail.html.twig' %}
{% include 'meeting/full-list.html.twig' %}
</div>
</div>
{% endblock %}
<file_sep><?php
namespace App\Form;
use App\Data\CancelData;
use App\Entity\Meeting;
use Faker\Core\Number;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CancelForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('explanation', TextareaType::class,[
'label'=>'The reason you are cancelling this meeting for :',
'required'=>true,
'help'=>'This cannot be undone',
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['data_class'=>CancelData::class,
'method'=>'GET',
'csrf_protection'=>false
]);
}
public function getBlockPrefix()
{
return '';
}
}<file_sep>{% extends 'base.html.twig' %}
{% block title %}{{ parent() }}Mot de pass oublié{% endblock %}
{% block body %}
<video autoplay muted loop class="myVideo">
<source src="{{ asset('assets/vid/login-black.mp4') }}" type="video/mp4">
</video>
<div class="request-content">
<h1>Mot de pass oublié</h1>
{{ form_start(resetForm) }}
{{ form_row(resetForm.plainPassword) }}
<button class="button">Mot de pass oublié</button>
{{ form_end(resetForm) }}</div>
{% endblock %}
<file_sep><?php
namespace App\DataFixtures;
use App\Entity\City;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
class CityFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
$faker = Factory::create('fr_FR');
for($i=1;$i<=20;$i++){
$city = new City();
$cpo = $faker->postcode;
$nom = $faker->city;
$city->setName($nom);
$city->setPostcode($cpo);
$manager->persist($city);
$this->setReference('city_'.$i,$city);
}
$manager->flush();
}
}
<file_sep><?php
namespace App\DataFixtures;
use App\Entity\Meeting;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
use phpDocumentor\Reflection\Types\This;
use function Sodium\add;
class MeetingsFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager)
{
$faker = Factory::create('fr_FR');
for ($i = 1;$i<=30;$i++) {
$meet = new Meeting();
$month = mt_rand(1,12);
$day = mt_rand(1,28);
$length = mt_rand(60,360);
$date = new \DateTime('2021-'.$month.'-'.$day);
$dateLater = new \DateTime('2021-'.$month.'-'.$day);
$dateLater->modify('-1 day');
$organizer = $this->getReference('user_'.mt_rand(1,30));
$campus = $this->getReference('campus_'.mt_rand(1,10));
$status = $this->getReference('state_'.mt_rand(1,6));
$place = $this->getReference('place_'.mt_rand(1,40));
$meet->setName('Sortie ' . 'des ' . $faker->jobTitle . ' ' . $faker->colorName)
->setTimeStarting($date)
->setLength($length)
->setRegisterUntil($dateLater)
->setMaxParticipants(mt_rand(10,30))
->setInformation($faker->paragraph(mt_rand(3,20)))
->setCampus($campus)
->setPlace($place)
->setStatus($status)
->setOrganisedBy($organizer);
for($j = 1; $j<=10;$j++){
$participants = $this->getReference('user_'.mt_rand(1,30));
$meet->addParticipant($participants);
}
$manager->persist($meet);
}
$manager->flush();
}
public function getDependencies()
{
return [UserFixtures::class,CampusFixtures::class,StateFixtures::class,PlaceFixtures::class];
}
}
<file_sep><?php
namespace App\Repository;
use App\Data\SearchData;
use App\Entity\Meeting;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Component\Pager\PaginatorInterface;
/**
* @method Meeting|null find($id, $lockMode = null, $lockVersion = null)
* @method Meeting|null findOneBy(array $criteria, array $orderBy = null)
* @method Meeting[] findAll()
* @method Meeting[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class MeetingRepository extends ServiceEntityRepository
{
private $paginator;
public function __construct(ManagerRegistry $registry , PaginatorInterface $paginator)
{
parent::__construct($registry, Meeting::class);
$this->paginator = $paginator;
}
public function findALlnoParameters(){
$queryBuilder = $this->createQueryBuilder('m');
$queryBuilder->distinct()
->select('m',
'mo',
'oc',
'mp',
'mpc',
's',
'p')
->innerJoin('m.organisedBy','mo')
->join('mo.campus','oc')
->innerJoin('m.place','mp')
->join('mp.city','mpc')
->join('m.status','s')
->leftJoin('m.participants','p');
$query = $queryBuilder->getQuery();
return $query->getResult();
}
public function findActive(SearchData $search,
User $user): Paginator
{
$currentTime = new \DateTime();
$currentTime->modify('- 30 days');
$timeOneMonth = $currentTime->format('Y-m-d');
$queryBuilder = $this->createQueryBuilder('m');
$queryBuilder->distinct()
->select('m',
'mo',
'oc',
'mp',
'mpc',
's',
'p')
->innerJoin('m.organisedBy','mo')
->join('mo.campus','oc')
->innerJoin('m.place','mp')
->join('mp.city','mpc')
->join('m.status','s')
->leftJoin('m.participants','p')
->andWhere('m.timeStarting >= :timeOneMonth')
->setParameter('timeOneMonth',"$timeOneMonth")
->orderBy('m.timeStarting')
;
if(!empty($search->q)) {
$queryBuilder = $queryBuilder
->andWhere('m.name LIKE :q')
->setParameter('q',"%{$search->q}%");
}
if(!empty($search->min)){
$queryBuilder = $queryBuilder
->andWhere('m.timeStarting >= :min')
->setParameter('min',"{$search->min->format('Y-m-d')}");
}
if(!empty($search->max)){
$queryBuilder = $queryBuilder
->andWhere('m.timeStarting <= :max')
->setParameter('max',"{$search->max->format('Y-m-d')}");
// dump($search->max->format('Y-m-d'));
// exit();
}
if(!empty($search->isOrganizedBy)){
$queryBuilder = $queryBuilder
->andWhere('m.organisedBy = '.$user->getId());
}
if(empty($search->isOver)){
$queryBuilder = $queryBuilder
->andWhere(" DATE_ADD(m.timeStarting,m.length, 'minute') >= CURRENT_DATE()");
}
if(!empty($search->isRegisteredTo)){
$queryBuilder = $queryBuilder
->andWhere('p.id IN (:id)')
->setParameter('id',$user->getId());
}
if(!empty($search->isNotRegisteredTo)){
$queryBuilder = $queryBuilder
->andWhere('p.id NOT IN (:id)')
->setParameter('id',$user->getId());
}
if(!empty($search->campus)){
$queryBuilder=$queryBuilder
->andWhere('m.campus = :campus')
->setParameter('campus',"{$search->campus->getId()}");
}
$query = $queryBuilder->getQuery();
//return $this->paginator->paginate($query,1,3);
return new Paginator($query);
}
// /**
// * @return Meeting[] Returns an array of Meeting objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('m')
->andWhere('m.exampleField = :val')
->setParameter('val', $value)
->orderBy('m.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Meeting
{
return $this->createQueryBuilder('m')
->andWhere('m.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<file_sep>{% extends 'base.html.twig' %}
{% block title %}
{% endblock %}
{% block body %}
<link rel="stylesheet" href="{{ asset('assets/css/groups.css') }}">
<div class="grid-container ">
<div class="grid-x app-group">
<div>test add members</div>
</div>
{% endblock %}
|
3347f4d332188c1dcb58bc7d7271b3cd3cf8f271
|
[
"Twig",
"Markdown",
"SQL",
"PHP"
] | 59 |
Twig
|
Valleaf/Sorties
|
55b8926da6a4bd88b6d60fa29f421802e92bbfe7
|
9bcfb47de48dc142e4e373c2015992e3f86ce78c
|
refs/heads/master
|
<repo_name>strange-jiong/programmableweb<file_sep>/pro2/pro2/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy import signals # ,log
import json
import codecs
from twisted.enterprise import adbapi
from datetime import datetime
from hashlib import md5
import MySQLdb
import MySQLdb.cursors
class Pro2Pipeline(object):
def __init__(self):
self.conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='',
db='test2',
)
self.conn.set_character_set('utf8')
self.cur = self.conn.cursor()
def process_item(self, item, spider):
# 2,3,12
# 这里存在一个序列化保存的问题,因为mysql支持的保存类型并没有,所以需要进行序列化来保存数据结构的类型
# 判断item的长度 存入不同的表中
if 'Followers_Name' in item.keys():
self.cur.execute("insert into api_followers (API_ID,Followers_Name) values(%s,%s)",
(json.dumps(item['API_ID']), json.dumps(item['Followers_Name'])))
print item
elif 'mushup_name' in item.keys() :
self.cur.execute("insert into api_mushup (API_ID,mushup_name) values(%s,%s)",
(json.dumps(item['API_ID']),
json.dumps(item['mushup_name'])
))
print item
else:
self.cur.execute("insert into api_info (API_Name,\
API_ID,\
Description,\
Primary_Category,\
Secondary_Categories,\
Followers_Number,\
API_Homepage,\
API_Provider) \
values(%s,%s,%s,%s,%s,%s,%s,%s)",
(json.dumps(item['API_Name']),
json.dumps(item['API_ID']),
json.dumps(item['Description']),
json.dumps(item['Primary_Category']),
json.dumps(item['Secondary_Categories']),
json.dumps(item['Followers_Number']),
json.dumps(item['API_Homepage']),
json.dumps(item['API_Provider'])
))
print item
# self.cur.close()
self.conn.commit()
# self.conn.close()
# return item
<file_sep>/pro2/create_txt.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Date : 2015-12-11 11:37:16
# @Author : jiong (<EMAIL>)
# @Version : $Id$
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import MySQLdb
import requests
import urllib2
import random
import json
conn = MySQLdb.connect(
host='10.13.75.146',
port=3306,
user='root',
passwd='',
db='api',
)
cur = conn.cursor()
cur.execute(
"select Description,Primary_Category,Secondary_Categories from api_info")
ret = cur.fetchall()
print 'length:', len(ret)
jiong = open('test.txt', 'w')
# jiong1=open('test2.txt','w')
count = []
tag_num = 0
# 得去掉description中间的空行
for each in ret[:200]:
try:
if json.loads(each[1]):
col1 = json.loads(each[0])
col1=col1.replace('\r','').replace('\n','').replace('\t','')
primary = json.loads(each[1])
secondary = json.loads(each[2])
temp = []
for a in primary:
temp.append(a)
for b in secondary:
temp.append(b)
for c in temp:
if c not in count:
tag_num += 1
count.append(c)
lable = ','.join(temp)
jiong.write('[' + lable + ']' + '\t' + col1 + '\n')
# jiong1.write(col2+'\t'+col1+'\n')
except Exception:
pass
print 'tag_num:', tag_num, len(count)
jiong.close()
# jiong1.close()
cur.close()
conn.commit()
conn.close()
<file_sep>/pro2/create_db.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-07 10:32:36
# @Author : jiong (<EMAIL>)
# @Version : $Id$
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import MySQLdb
import subprocess
import os
os.system('net start MySql')
subprocess.Popen(['mysql','-uroot',])
# subprocess.Popen(['CREATE DATABASE `test2` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci'])
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='',
db ='jiong_test',
)
cur = conn.cursor()
#创建数据表
# cur.execute("CREATE DATABASE test1 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci")
cur.execute("DROP TABLE IF EXISTS api_info")
cur.execute("DROP TABLE IF EXISTS api_followers")
cur.execute("DROP TABLE IF EXISTS api_mushup")
cur.execute("create table api_info(API_Name varchar(200) ,\
API_ID varchar(20),\
Description varchar(3000),\
Primary_Category varchar(100),\
Secondary_Categories varchar(300),\
Followers_Number varchar(30),\
API_Homepage varchar(300),\
API_Provider varchar(300))")
cur.execute("create table api_followers(API_ID varchar(20) ,\
Followers_Name varchar(3000) )")
cur.execute("create table api_mushup(API_ID varchar(20) ,\
mushup_name varchar(3000))")
cur.close()
conn.commit()
conn.close()
<file_sep>/pw_followers/pw.py
# -*- coding: utf-8 -*-
import urllib
import urllib2
import requests
import cookielib
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
"""
entrance
http://www.programmableweb.com/category/all/apis
destination
http://www.programmableweb.com/api/forecast/followers
爬取pw网站的api的followers信息
"""
def get_api_name(url):
"""
获取每一页上的api的name
"""
print '正在获取api_name...'
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open(url)
html = response.read()
api_name = re.findall(r' <a href="/api/(.+?)">', html)
# print api_name
return api_name
# pass
def get_followers(name):
print '正在获取%s的followers...' % name
url = "http://www.programmableweb.com/api/%s/followers" % name
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open(url)
html = response.read()
followers = re.findall(r' <a href="/profile/(.+?)"><img src=', html)
followers_num = int(re.findall(
r"<div class='block-title'><span>Followers \((.+?)\)", html)[0])
print 'followers_num:', followers_num
# print followers
# print len(followers)
return followers, followers_num, opener
def get_followers_more(api_name, followers_num, opener):
"""
如果超过一页所能显示的量(100个),则继续执行此函数
"""
print 'followers_num多余100,正在获取%s的其余follwers' % api_name
url = 'http://www.programmableweb.com/api/%s/followers?pw_view_display_id=list_all&page=' % name
followers_url = [url + '%d' %
num for num in range(1, followers_num / 100 + 2)]
followers = []
for url in followers_url:
response = opener.open(url)
html = response.read()
followers.extend(re.findall(
r' <a href="/profile/(.+?)"><img src=', html))
return followers
if __name__ == '__main__':
# get_followers()
init_url = 'http://www.programmableweb.com/category/all/apis'
start_url = ["http://www.programmableweb.com/category/all/apis?page=%d" %
a for a in range(1, 528)]
start_url.append(init_url)
# print start_url
for url in start_url:
api_name = get_api_name(url)
for name in api_name:
followers, followers_num, opener = get_followers(name)
if followers_num > 100:
followers[len(followers):len(followers)] = get_followers_more(
name, followers_num, opener)
try:
file = open('.\\followers.txt', 'a')
file.write(name + '\t' + '\t'.join(followers) + '\n')
except Exception, e:
pass
finally:
file.close()
<file_sep>/pro2/pro2/spiders/progm.py
# -*- coding: utf-8 -*-
import scrapy
import scrapy
from scrapy.http import Request
from pro2.items import programmable, followers, mushup
# import time
# from selenium import webdriver
# import json
# import re
class ProgmSpider(scrapy.Spider):
name = "progm"
allowed_domains = ["programmableweb.com"]
url = 'http://www.programmableweb.com/category/all/apis'
# http://www.programmableweb.com/category/all/apis?page=1
url1 = 'http://www.programmableweb.com/category/all/apis?search_id=147085&deadpool=1'
# http://www.programmableweb.com/category/all/apis?page=142&search_id=147085&deadpool=1
start_url = ["http://www.programmableweb.com/category/all/apis?page=%d&search_id=147085&deadpool=1" %
a for a in range(1, 144)]
start_url.append(url1)
start_urls = start_url
def parse(self, response):
for sel in response.xpath('//td[@class="views-field views-field-title col-md-3"]/a/@href').extract():
url = 'http://www.programmableweb.com' + sel
# print url
yield Request(url, callback=self.parse2)
def parse2(self, response):
item = programmable()
item['API_Name'] = response.xpath(
"""//*[@class="node-header"]/h1/text()""").extract()
item['API_ID'] = response.xpath(
"""//li[@class="last leaf pull-left text-uppercase"]/a/@href""").extract()[0].split('/')[-1]
item['Description'] = response.xpath(
"""//div[@class="api_description tabs-header_description"]/text()""").extract()[0].strip()
item['Primary_Category'] = []
item['Secondary_Categories'] = []
item['API_Homepage']=[]
# 部分网页的格式是不一样的 遍历所有的div元素来找出所要的信息
for sel in response.xpath('//div[@class="section specs"]/div[@class="field"]'):
if sel.xpath('label/text()').extract()[0] == 'Secondary Categories':
item['Secondary_Categories'] = sel.xpath(
'span/a/text()').extract()
if sel.xpath('label/text()').extract()[0] == 'Primary Category':
item['Primary_Category'] = sel.xpath(
'span/a/text()').extract()
if sel.xpath('label/text()').extract()[0]=='API Homepage':
item['API_Homepage']=sel.xpath('span/a/text()').extract()
if sel.xpath('label/text()').extract()[0]=='API Provider':
item['API_Provider']=sel.xpath('span/a/text()').extract()
item['Followers_Number'] = response.xpath(
"""//section[@id="block-views-api-followers-row-top"]/div[1]/span/text()""").extract()
# 示例网址:http://www.programmableweb.com/api/quova/followers
yield item
url2 = response.url + '/followers'
yield Request(url2, callback=self.parse3)
# musghups
# //*[@id='block-views-api-mashups-new-list-top']/div[2]/div[1]/a
url3 = "http://www.programmableweb.com" + \
response.xpath(
"//*[@id='block-views-api-mashups-new-list-top']/div[2]/div[1]/a/@href").extract()[0]
yield Request(url3, callback=self.parse4)
def parse3(self, response):
# 如果follows数量超过一百,在一页上显示不全 最多100个
item = followers()
# //*[@id='followers']/div[2]/div[2]/table/tbody/tr[1]/td[2]/a
# //*[@id='followers']/div[2]/div[2]/table/tbody/tr[2]/td[2]/a
# //*[@id='followers']/div[2]/div[2]/table/tbody/tr[17]/td[2]/a
# //*[@id='followers']/div[2]/div[2]/table/tbody/tr[1]/td[2]/a
item['API_ID'] = response.xpath(
'//li[@class="last leaf pull-left text-uppercase"]/a/@href').extract()[0].split('/')[-2]
item['Followers_Name'] = []
for sel in response.xpath("//*[@id='followers']/div[2]/div[2]/table/tbody/tr/td[2]/a"):
temp = sel.xpath('text()').extract()[0]
item['Followers_Name'].append(temp)
yield item
def parse4(self, response):
# //*[@id='block-system-main']/article/div[7]/div[1]/table/tbody/tr[1]/td[1]/a
# //*[@id='block-system-main']/article/div[7]/div[1]/table/tbody/tr[2]/td[1]/a
# //*[@id='block-system-main']/article/div[7]/div[1]/table/tbody/tr[1]/td[1]/a
item = mushup()
item['API_ID'] = response.url.split('=')[-1]
item['mushup_name'] = []
for sel in response.xpath("//*[@id='block-system-main']/article/div[7]/div[1]/table/tbody/tr/td[1]/a"):
temp = sel.xpath('text()').extract()[0]
item['mushup_name'].append(temp)
yield item
<file_sep>/pw_followers/README.md
#programmableweb
##Followers of the API
***v0.1 Second release of pw 2016 Mar***<file_sep>/pro2/pro2/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Pro2Item(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
class programmable(scrapy.Item):
"""docstring for ClassName"""
API_Name = scrapy.Field()
API_ID = scrapy.Field()
Description = scrapy.Field()
Primary_Category = scrapy.Field()
Secondary_Categories = scrapy.Field()
Followers_Number = scrapy.Field()
Followers_Id = scrapy.Field()
API_Homepage=scrapy.Field()
API_Provider=scrapy.Field()
class followers(scrapy.Item):
API_ID = scrapy.Field()
Followers_Name = scrapy.Field()
class mushup(scrapy.Item):
API_ID = scrapy.Field()
mushup_name = scrapy.Field()
<file_sep>/pro2/select_api.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Date : 2015-12-11 11:37:16
# @Author : jiong (<EMAIL>)
# @Version : $Id$
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import MySQLdb
import requests,urllib2,random
import json
print '123'
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='',
db ='test2',
)
cur = conn.cursor()
cur.execute("select API_ID,Primary_Category,Secondary_Categories from api_info")
ret = cur.fetchall()
print ret[0]
print ret[0]
jiong=open('test3.txt','w')
# jiong1=open('test4.txt','w')
n=0
tem=['Mapping','Social','eCommerce','Tools','Search','Mobile','API','Video','Messaging','Financial']
try:
for each in ret:
if json.loads(each[1]) :
col1=json.loads(each[0])
col2=json.loads(each[1])[0]
# print len(each)
if len(each)==3:
try:
col3=json.loads(each[2])
except Exception,e:
col3=[]
print 'error!!!!!',e
finally:
pass
# if col2=='Mapping' or col2=='Social' or col2=='eCommerce' or col2=='Tools' or col2=='Search' or col2=='Mobile' or col2=='API' or col2=='Video' or col2=='Messaging' or col2=='Financial':
else:
col3=[]
col3.append(col2)
for a in col3:
# print a
if a in tem:
jiong.write(col1+'\t'+a+'\n')
n+=1
# continue
break
# jiong1.write(col2+'\t'+col1+'\n')
jiong.write(str(n))
jiong.close()
print n
except Exception,e:
print 'error!!!!!',e
# jiong1.close()<file_sep>/google_api/api_info.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @Date : 2015-12-11 11:37:16
# @Author : jiong (<EMAIL>)
# @Version : $Id$
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import MySQLdb
import requests
import urllib2
import random
from lxml import etree
import json
import time
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='',
db='api2',
)
cur = conn.cursor()
cur.execute("select API_ID,API_Homepage from api_info ")
ret = cur.fetchall()
cur.close()
conn.commit()
conn.close()
# print ret
user_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533+ \
(KHTML, like Gecko) Element Browser 5.0',
'IBM WebExplorer /v0.94', 'Galaxy/1.0 [en] (Mac OS X 10.5.6; U; en)',
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14',
'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) \
Version/6.0 Mobile/10A5355d Safari/8536.25',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/28.0.1468.0 Safari/537.36',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; TheWorld)']
# queryStr='http://allogarage.wordpress.com/2007/11/15/api-allogarage/'
for each in ret:
# 排除掉HOMEpage为空以及不是url形式的信息
if json.loads(each[1]) and str(json.loads(each[1])[0]).startswith('http'):
queryStr = json.loads(each[1])[0]
# print json.loads(each[0])
# print json.loads(each[1])[0]
queryStr = urllib2.quote(queryStr)
# print queryStr
url = 'https://www.google.com.hk/search?q=%s&newwindow=1&safe=active&hl=en&lr=lang_en&sa=X&ved=0ahUKEwi9kcu8x-XJAhUHIqYKHW1dCfQQuAEIIA&biw=1440&bih=775' % queryStr
request = urllib2.Request(url)
index = random.randint(0, 9)
user_agent = user_agents[index]
request.add_header('User-agent', user_agent)
response = urllib2.urlopen(request)
html = response.read()
selector = etree.HTML(html)
info = selector.xpath(
'//*[@id="rso"]/div/div[1]/div/div/div/span/text()')
if not info:
info = selector.xpath(
'//*[@id="rso"]/div[1]/div/div/div/div/span/text()')
if not info:
info = selector.xpath(
'//*[@id="rso"]/div/div/div[1]/div/div/span/text()')
print each[0], info
# conn= MySQLdb.connect(
# host='localhost',
# port = 3306,
# user='root',
# passwd='',
# db ='test3',
# )
# cur = conn.cursor()
# cur.execute("insert into api_google (API_ID,description) values(%s,%s)",
# (each[0], json.dumps(info)))
# ret = cur.fetchall()
# cur.close()
# conn.commit()
# conn.close()
# time.sleep(7)
# //*[@id="rso"]/div/div[1]/div/div/div/span
# //*[@id="rso"]/div[1]/div/div/div/div/span
# //*[@id="rso"]/div/div[1]/div/div/div/span
<file_sep>/README.md
#programmableweb spider
##Installation:
近日,API通用资源网站ProgrammableWeb宣布,该网站目录中的API已突破5,000大关,并预言最终所有公司都将拥有自己的API,其中甚至还包括政府官网。
**信息来源时间:2012-02-07**
依赖包:
- scrapy 安装 pip install scrapy
- MySQLdb 安装 pip install MySQL-python
Now 2015.1
##Usage:
scrapy crawl \[spider_name\]
因为[ProgrammableWeb网站](www.programmableweb.com)好像并没有反爬虫限制,所以应该会爬得比较顺利。
##problems:
之前的版本这几天重新拿出来跑的时候发现一开始的入口url不对,可能是pw网站存在定时更新api的情况,网站所提供的api信息的url有所变化,需要再次修改。
***v0.1 Second release of pw 2016 Mar***
|
d4af6983a47c5b3fe408cbe1d08f3afa835bee18
|
[
"Markdown",
"Python"
] | 10 |
Markdown
|
strange-jiong/programmableweb
|
3059702c5f60da88d060742a102f1288373acfe0
|
887ab4a00d9958c96d57eaf1be3005e763cf98bf
|
refs/heads/main
|
<repo_name>CheneyChenStar/CoreBlog<file_sep>/src/WebApiCore/CustomClass/CustomActionAndResultFilter.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Linq;
namespace Ligy.Project.WebApi.CustomClass
{
public class CustomActionAndResultFilter : Attribute, IActionFilter, IResultFilter
{
private readonly ILogger<CustomActionAndResultFilter> _logger = null;
public CustomActionAndResultFilter(ILogger<CustomActionAndResultFilter> logger)
{
_logger = logger;
}
public void OnActionExecuting(ActionExecutingContext context)
{
var sLog = $"【Controller】:{context.RouteData.Values["controller"]}\r\n" +
$"【Action】:{context.RouteData.Values["action"]}\r\n" +
$"【Paras】:{(context.ActionArguments.Count != 0 ? JsonConvert.SerializeObject(context.ActionArguments) : "None")}";
_logger.LogInformation(sLog);
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnResultExecuted(ResultExecutedContext context)
{
}
public void OnResultExecuting(ResultExecutingContext context)
{
var sLog = $"【Controller】:{context.RouteData.Values["controller"]}\r\n" +
$"【Action】:{context.RouteData.Values["action"]}\r\n";
_logger.LogInformation(sLog);
if (!context.ModelState.IsValid)
{
var result = context.ModelState.Keys
.SelectMany(key => context.ModelState[key].Errors.Select(x => new ValidationError(key, x.ErrorMessage)));
context.Result = new ObjectResult(
new ResultModel(
code: 422,
message: "参数不合法",
result: result,
returnStatus: ReturnStatus.Fail)
);
}
else
{
context.Result = new ObjectResult(
new ResultModel(
code: 100,
message: "成功",
result: (context.Result as ObjectResult)?.Value,
returnStatus: ReturnStatus.Success)
);
}
}
}
}
<file_sep>/src/WebApiCore.Entity/DataBase/SqlServerDB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApiCore.EF.DataBase
{
/// <summary>
/// SqlServer数据库
/// </summary>
internal class SqlServerDB : BaseDatabase
{
internal SqlServerDB(string provider, string connStr) : base(provider, connStr)
{
}
}
}
<file_sep>/src/WebApiCore.EF/BlogInfos/Profile.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApiCore.Entity.BlogInfos
{
[Table("t_sys_profile")]
public class Profile :BaseEntity
{
public string Name { get; set; }
public Blog Blog { get; set; }
}
}
<file_sep>/src/WebApiCore/CustomClass/CustomAutofacModule.cs
using Autofac;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Ligy.Project.WebApi.CustomClass
{
public class CustomAutofacModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
Assembly iservice = Assembly.Load("WebApiCore.Interface");
string localPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly service = Assembly.LoadFrom(Path.Combine(localPath, "WebApiCore.Service.dll"));
builder.RegisterAssemblyTypes(service, iservice)
.InstancePerLifetimeScope()
.AsImplementedInterfaces()
.PropertiesAutowired();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(x => x.Name.EndsWith("Controller")).PropertiesAutowired();
}
}
}
<file_sep>/src/WebApiCore.Utils/Browser/BaseBrowser.cs
using System;
namespace WebApiCore.Utils.Browser
{
internal class BaseBrowser
{
public string Name { get; set; }
public string Maker { get; set; }
public BrowserType Type { get; set; } = BrowserType.Generic;
public Version Version { get; set; }
public BaseBrowser() { }
public BaseBrowser(BrowserType browserType) => Type = browserType;
public BaseBrowser(BrowserType browserType, Version version) : this(browserType) => Version = version;
public BaseBrowser(string name)
{
}
public Version ToVersion(string version)
{
version = RemoveWhitespace(version);
return Version.TryParse(version, out var parsedVersion) ? parsedVersion : new Version(0, 0);
}
public string RemoveWhitespace(string version) => version?.Replace(" ", "", StringComparison.OrdinalIgnoreCase);
}
}
<file_sep>/src/WebApiCore.EF/BaseEntity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace WebApiCore.Entity
{
public class BaseEntity
{
[Key]
public int Id { get; set; }
public DateTime CreateTime { get; set; }
public DateTime ModifyTime { get; set; }
}
}
<file_sep>/src/WebApiCore/CustomClass/CustomResourceFilter.cs
using Microsoft.AspNetCore.Mvc.Filters;
using System;
namespace Ligy.Project.WebApi.CustomClass
{
/// <summary>
/// 缓存作用,在控制器实例化前被调用
/// </summary>
public class CustomResourceFilterAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
}
}
<file_sep>/src/WebApiCore.Service/BlogService.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WebApiCore.EF;
using WebApiCore.Entity.BlogInfos;
using WebApiCore.Interface;
using WebApiCore.Utils.Model;
namespace WebApiCore.Service
{
public class BlogService : IBlogService
{
public async Task<IEnumerable<Blog>> GetBlogs()
{
//var page = new PaginationParam();
//var (total, lis) = await InitDB.Create().FindListAsync<Blog>(page.SortColumn, page.IsASC, page.PageSize, page.CurrentPage);
//return lis;
var aaa = await InitDB.Create().FindObjectAsync("delete from t_sys_blog");
return (IEnumerable<Blog>)aaa;
}
}
}
<file_sep>/src/WebApiCore.Utils/Browser/BrowserType.cs
namespace WebApiCore.Utils.Browser
{
internal enum BrowserType
{
IE,
Chrome,
Safari,
Firefox,
Edge,
Opera,
Generic
}
}
<file_sep>/src/WebApiCore.Entity/DataBase/DBExtension.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace WebApiCore.EF.DataBase
{
public class DBExtension
{
/// <summary>
/// 分页帮助
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tmpData"></param>
/// <param name="sort"></param>
/// <param name="isAsc"></param>
/// <returns></returns>
public static IQueryable<T> PaginationSort<T>(IQueryable<T> tmpData, string sort, bool isAsc) where T : class, new()
{
string[] sortArr = sort.Split(',');
MethodCallExpression resultExpression = null;
for (int index = 0; index < sortArr.Length; index++)
{
string[] sortColAndRuleArr = sortArr[index].Trim().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
string sortField = sortColAndRuleArr.First();
bool sortAsc = isAsc;
//排序列带上规则 "Id Asc"
if (sortColAndRuleArr.Length == 2)
{
sortAsc = string.Equals(sortColAndRuleArr[1], "asc", StringComparison.OrdinalIgnoreCase);
}
var parameter = Expression.Parameter(typeof(T), "type");
var property = typeof(T).GetProperties().First(p => p.Name.Equals(sortField));
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
if (index == 0)
{
resultExpression = Expression.Call(
typeof(Queryable), //调用的类型
sortAsc ? "OrderBy" : "OrderByDescending", //方法名称
new[] { typeof(T), property.PropertyType }, tmpData.Expression, Expression.Quote(orderByExpression));
}
else
{
resultExpression = Expression.Call(
typeof(Queryable),
sortAsc ? "ThenBy" : "ThenByDescending",
new[] { typeof(T), property.PropertyType }, tmpData.Expression, Expression.Quote(orderByExpression));
}
tmpData = tmpData.Provider.CreateQuery<T>(resultExpression);
}
return tmpData;
}
}
}
<file_sep>/src/WebApiCore.Utils/Model/PaginationParam.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApiCore.Utils.Model
{
/// <summary>
/// 分页参数
/// </summary>
public class PaginationParam
{
/// <summary>
/// 每页行数
/// </summary>
public int PageSize { get; set; } = 10;//默认10行数据
/// <summary>
/// 当前页
/// </summary>
public int CurrentPage { get; set; } = 1;
/// <summary>
/// 排序列
/// </summary>
public string SortColumn { get; set; } = "Id"; //默认Id为排序列
/// <summary>
/// 排序类型
/// </summary>
public bool IsASC { get; set; } = false;
/// <summary>
/// 总记录数
/// </summary>
public int TotalCount { get; set; }
/// <summary>
/// 总页数
/// </summary>
public int PageCount
{
get
{
if (TotalCount > 0)
{
return (TotalCount % PageSize) == 0
? TotalCount / PageSize
: TotalCount / PageSize + 1;
}
else
{
return 0;
}
}
}
}
}
<file_sep>/src/WebApiCore.Utils/Browser/BrowserHelper.cs
using System;
namespace WebApiCore.Utils.Browser
{
internal class BrowserHelper
{
public static string GetBrwoserInfo(string userAgent)
{
var ie = new InternetExplorer(userAgent);
if (ie.Type == BrowserType.IE)
return string.Format("{0} {1}", ie.Type.ToString(), ie.Version);
var firefox = new Firefox(userAgent);
if (firefox.Type == BrowserType.Firefox)
return string.Format("{0} {1}", firefox.Type.ToString(), firefox.Version);
var edge = new Edge(userAgent);
if (edge.Type == BrowserType.Edge)
return string.Format("{0} {1}", edge.Type.ToString(), edge.Version);
var opera = new Opera(userAgent);
if (opera.Type == BrowserType.Opera)
return string.Format("{0} {1}", opera.Type.ToString(), opera.Version);
var chrome = new Chrome(userAgent);
if (chrome.Type == BrowserType.Chrome)
return string.Format("{0} {1}", chrome.Type.ToString(), chrome.Version);
var safari = new Safari(userAgent);
if (safari.Type == BrowserType.Safari)
return string.Format("{0} {1}", safari.Type.ToString(), safari.Version);
throw new ArgumentException("找不到符合的浏览器类型!");
}
}
}
<file_sep>/src/WebApiCore/Program.cs
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Ligy.Project.WebApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureLogging(logbuilder =>
{
logbuilder.AddFilter("System", LogLevel.Warning)
.AddFilter("Microsoft", LogLevel.Warning)
.AddLog4Net();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
<file_sep>/src/WebApiCore.Entity/DataBase/BaseDatabase.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WebApiCore.Entity.BlogInfos;
namespace WebApiCore.EF.DataBase
{
public abstract class BaseDatabase : IDataBaseOperation
{
public BaseDatabase(string provider, string connStr)
{
_dbContext = new MyDbContext(provider, connStr);
}
public IDataBaseOperation GetIDataBaseOperation()
{
return this;
}
#region Fields
private readonly DbContext _dbContext = null;
private IDbContextTransaction _dbContextTransaction = null;
#endregion
#region Properties
public DbContext DbContext { get => _dbContext; }
public IDbContextTransaction DbContextTransaction { get => _dbContextTransaction; }
#endregion
#region Transcation Operate
public virtual async Task<IDataBaseOperation> EnsureDeletedAsync()
{
await _dbContext.Database.EnsureDeletedAsync();
return this;
}
public virtual async Task<IDataBaseOperation> EnsureCreatedAsync()
{
await _dbContext.Database.EnsureCreatedAsync();
return this;
}
public virtual async Task<IDataBaseOperation> BeginTransAsync()
{
var conn = _dbContext.Database.GetDbConnection();
if (conn.State == ConnectionState.Closed)
{
await conn.OpenAsync();
}
_dbContextTransaction = await _dbContext.Database.BeginTransactionAsync();
return this;
}
public virtual async Task<int> CommitTransAsync()
{
try
{
int taskResult = await _dbContext.SaveChangesAsync();
if (_dbContextTransaction != null)
{
await _dbContextTransaction.CommitAsync();
}
await this.CloseAsync();
return taskResult;
}
catch
{
//throw exception
throw;
}
finally
{
if (_dbContextTransaction == null)
{
await this.CloseAsync();
}
}
}
public virtual async Task RollbackTransAsync()
{
if (_dbContextTransaction != null)
{
await _dbContextTransaction.RollbackAsync();
await _dbContextTransaction.DisposeAsync();
await this.CloseAsync();
}
}
public virtual async Task<IDataBaseOperation> CreateSavepointAsync(string name)
{
IDataBaseOperation operation = _dbContextTransaction == null
? await BeginTransAsync()
: this;
await _dbContextTransaction.CreateSavepointAsync(name);
return operation;
}
public virtual async Task RollbackToSavepointAsync(string name)
{
if (_dbContextTransaction != null)
{
await _dbContextTransaction.RollbackToSavepointAsync(name);
}
}
public virtual async Task CloseAsync()
{
await _dbContext.DisposeAsync();
}
#endregion
#region Sql Exec
public virtual async Task<int> ExecuteSqlRawAsync(string strSql)
{
await _dbContext.Database.ExecuteSqlRawAsync(strSql);
return await GetReuslt();
}
public virtual async Task<int> ExecuteSqlRawAsync(string strSql, params DbParameter[] dbParameter)
{
await _dbContext.Database.ExecuteSqlRawAsync(strSql, dbParameter);
return await GetReuslt();
}
public virtual async Task<int> ExecuteSqlInterpolatedAsync(FormattableString strSql)
{
await _dbContext.Database.ExecuteSqlInterpolatedAsync(strSql);
return await GetReuslt();
}
public virtual async Task<int> ExecuteByProcAsync(string procName)
{
await this.ExecuteSqlRawAsync($"EXEC {procName}");
return await GetReuslt();
}
public virtual async Task<int> ExecuteByProcAsync(string procName, DbParameter[] dbParameter)
{
await this.ExecuteSqlRawAsync(procName, dbParameter);
return await GetReuslt();
}
#endregion
#region Insert
public virtual async Task<int> InsertAsync<T>(T entity) where T : class
{
_dbContext.Set<T>().Add(entity);
return await GetReuslt();
}
public virtual async Task<int> InsertAsync(params object[] entities)
{
await _dbContext.AddRangeAsync(entities);
return await GetReuslt();
}
public virtual async Task<int> InsertAsync<T>(IEnumerable<T> entities) where T : class
{
await _dbContext.Set<T>().AddRangeAsync(entities);
return await GetReuslt();
}
#endregion
#region Delete
public virtual async Task<int> DeleteAsync<T>(T entity) where T : class
{
_dbContext.Set<T>().Remove(entity);
return await GetReuslt();
}
public virtual async Task<int> DeleteAsync(params object[] entities)
{
_dbContext.RemoveRange(entities);
return await GetReuslt();
}
public virtual async Task<int> DeleteAsync<T>(IEnumerable<T> entities) where T : class
{
_dbContext.Set<T>().RemoveRange(entities);
return await GetReuslt();
}
public virtual async Task<int> DeleteAsync<T>(int id) where T : class
{
IEntityType entityType = _dbContext.Set<T>().EntityType;
if (entityType == null)
{
throw new ArgumentException($"类型{entityType.Name}不符合跟踪要求!");
}
string tableNae = entityType.GetTableName();
string fieldKey = "Id";
return await this.ExecuteSqlRawAsync($"Delete From {tableNae} where {fieldKey}={id};");
}
public virtual async Task<int> DeleteAsync<T>(IEnumerable<int> ids) where T : class
{
IEntityType entityType = _dbContext.Set<T>().EntityType;
if (entityType == null)
{
throw new ArgumentException($"类型{entityType.Name}不符合跟踪要求!");
}
string tableNae = entityType.GetTableName();
string fieldKey = "Id";
StringBuilder sb = new StringBuilder(ids.Count() + 1);
sb.Append($"Delete From {tableNae} \r\n where 1=1 and ( ");
sb.AppendJoin(" or ", ids.Select(x => $" {fieldKey} = {x} "));
sb.Append(" );");
return await this.ExecuteSqlRawAsync(sb.ToString());
}
public virtual async Task<int> DeleteAsync<T, TProp>(TProp propertyName, TProp propertyValue) where TProp : MemberInfo where T : class
{
IEntityType entityType = _dbContext.Set<T>().EntityType;
if (entityType == null)
{
throw new ArgumentException($"类型{entityType.Name}不符合跟踪要求!");
}
string tableNae = entityType.GetTableName();
return await this.ExecuteSqlRawAsync($"Delete From {tableNae} where {propertyName.Name}='{propertyValue}';");
}
#endregion
public virtual async Task<T> FindEntityAsync<T>(object KeyValue) where T : class
{
return await _dbContext.Set<T>().FindAsync(KeyValue);
}
public virtual async Task<T> FindEntityAsync<T>(Expression<Func<T, bool>> predicate) where T : class, new()
{
return await _dbContext.Set<T>().Where(predicate).FirstOrDefaultAsync();
}
public virtual async Task<IEnumerable<T>> FindListAsync<T>() where T : class, new()
{
return await _dbContext.Set<T>().ToListAsync();
}
public virtual async Task<IEnumerable<T>> FindListASCAsync<T>(Expression<Func<T, object>> predicate) where T : class, new()
{
return await _dbContext.Set<T>().OrderBy(predicate).ToListAsync();
}
public virtual async Task<IEnumerable<T>> FindListDESCAsync<T>(Expression<Func<T, object>> predicate) where T : class, new()
{
return await _dbContext.Set<T>().OrderByDescending(predicate).ToListAsync();
}
public virtual async Task<IEnumerable<T>> FindListAsync<T>(Expression<Func<T, bool>> predicate) where T : class, new()
{
return await _dbContext.Set<T>().Where(predicate).ToListAsync();
}
public virtual async Task<(int total, IEnumerable<T> list)> FindListAsync<T>(string sort, bool isAsc, int pageSize, int pageIndex) where T : class, new()
{
var tmpData = _dbContext.Set<T>().AsQueryable();
return await FindListAsync<T>(tmpData, sort, isAsc, pageSize, pageIndex);
}
private async Task<(int total, IEnumerable<T> list)> FindListAsync<T>(IQueryable<T> tmpdata, string sort, bool isAsc,
int pageSize, int pageIndex) where T : class, new()
{
tmpdata = DBExtension.PaginationSort<T>(tmpdata, sort, isAsc);
var list = await tmpdata.ToListAsync();
if (list?.Count > 0)
{
var currentData = list.Skip<T>(pageSize * (pageIndex - 1)).Take<T>(pageSize);
return (list.Count, currentData);
}
else
{
return (0, new List<T>());
}
}
public virtual async Task<(int total, IEnumerable<T> list)> FindListAsync<T>(Expression<Func<T, bool>> condition, string sort,
bool isAsc, int pageSize, int pageIndex) where T : class, new()
{
var tempData = _dbContext.Set<T>().Where(condition);
return await FindListAsync<T>(tempData, sort, isAsc, pageSize, pageIndex);
}
public virtual async Task<object> FindObjectAsync(string strSql)
{
return await this.FindObjectAsync(strSql, null);
}
public virtual async Task<object> FindObjectAsync(string strSql, DbParameter[] dbParameter)
{
return await DBHelper.GetInstance(_dbContext).GetScalar(strSql, dbParameter);
}
public virtual async Task<DataTable> FindTableAsync(string strSql)
{
return await this.FindTableAsync(strSql, null);
}
public virtual async Task<DataTable> FindTableAsync(string strSql, DbParameter[] dbParameter)
{
return await DBHelper.GetInstance(_dbContext).GetDataTable(strSql, dbParameter);
}
public virtual IQueryable<T> IQueryableAsync<T>(Expression<Func<T, bool>> predicate) where T : class, new()
{
return _dbContext.Set<T>().Where(predicate);
}
public virtual async Task<int> UpdateAsync<T>(T entity) where T : class
{
_dbContext.Set<T>().Update(entity);
return await GetReuslt();
}
public virtual async Task<int> UpdateAsync<T>(IEnumerable<T> entities) where T : class
{
_dbContext.Set<T>().UpdateRange(entities);
return await GetReuslt();
}
public virtual async Task<int> UpdateAllFieldAsync<T>(T entity) where T : class
{
_dbContext.Set<T>().Update(entity);
return await GetReuslt();
}
private async Task<int> GetReuslt()
{
return _dbContextTransaction == null//当前事务
? await this.CommitTransAsync() //没有事务立即提交
: 0; //有事务就返回0;
}
}
}
<file_sep>/src/WebApiCore.Utils/Model/DBConfig.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace WebApiCore.Utils.Model
{
public class DBConfig
{
public string Provider { get; set; }
public string SqlServerConnectionString { get; set; }
public string MySqlConnectionString { get; set; }
public int Timeout { get; set; }
public int DBSlowSqlLogTime { get; set; }
}
}
<file_sep>/src/WebApiCore.Utils/Model/SystemConfig.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace WebApiCore.Utils.Model
{
public class SystemConfig
{
public DBConfig DBConfig { get; set; }
public string CacheProvider { get; set; }
}
}
<file_sep>/src/WebApiCore/Controllers/EFTestsController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using WebApiCore.Entity.BlogInfos;
using WebApiCore.Interface;
namespace Ligy.Project.WebApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class EFTestsController : ControllerBase
{
public IBlogService BlogService { get; set; }
[HttpGet]
public async Task<IEnumerable<Blog>> GetBlogs()
{
return await BlogService.GetBlogs();
}
}
}
<file_sep>/src/WebApiCore.Entity/InitDB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApiCore.EF.DataBase;
using WebApiCore.Utils;
namespace WebApiCore.EF
{
/// <summary>
/// 初始化数据库上下文
/// </summary>
public class InitDB
{
public static IDataBaseOperation Create(string provider = null, string connStr = null)
{
provider = GlobalInvariant.SystemConfig?.DBConfig?.Provider ?? provider;
switch (provider)
{
case "SqlServer":
connStr = GlobalInvariant.SystemConfig?.DBConfig?.SqlServerConnectionString ?? connStr;
return new SqlServerDB(provider, connStr).GetIDataBaseOperation();
case "MySql":
connStr = GlobalInvariant.SystemConfig?.DBConfig?.MySqlConnectionString ?? connStr;
return new MySqlDB(provider, connStr).GetIDataBaseOperation();
default:
throw new NotImplementedException("未知的数据引擎");
}
}
}
}
<file_sep>/src/WebApiCore.Entity/DataBase/DBHelper.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApiCore.EF.DataBase
{
public sealed class DBHelper
{
private DBHelper() { }
private static DbContext _dbContext = null;
private readonly static DBHelper _dbHelper = new DBHelper();
public static DBHelper GetInstance(DbContext dbContext)
{
_dbContext = dbContext;
return _dbHelper;
}
/// <summary>
/// 创建DbCommand对象,打开连接,打开事务
/// </summary>
/// <param name="sql">执行语句</param>
/// <param name="parameters">参数数组</param>
/// <returns>DbCommand</returns>
private async Task<DbCommand> CreateDbCommand(string sql, DbParameter[] parameters)
{
try
{
DbConnection dbConnection = _dbContext.Database.GetDbConnection();
DbCommand command = dbConnection.CreateCommand();
command.CommandText = sql;
if (parameters != null && parameters.Length != 0)
{
command.Parameters.AddRange(parameters);
}
if (command.Connection.State == ConnectionState.Closed)
{
await command.Connection.OpenAsync();
}
return command;
}
catch
{
throw;
}
finally
{
await this.CloseAsync();
}
}
/// <summary>
/// 执行sql
/// </summary>
/// <param name="sql">sql</param>
/// <returns>返回受影响行数<see cref="int"/></returns>
public async Task<int> RunSql(string sql)
{
return await RunSql(sql, null);
}
/// <summary>
/// 执行查询语句
/// </summary>
/// <param name="sql">执行语句</param>
/// <param name="parameters">参数数组</param>
/// <returns>受影响的行数<see cref="int"/></returns>
public async Task<int> RunSql(string sql, DbParameter[] parameters)
{
using DbCommand cmd = await CreateDbCommand(sql, parameters);
try
{
int iRes = await cmd.ExecuteNonQueryAsync();
if (cmd.Transaction != null)
{
await cmd.Transaction.CommitAsync();
}
await this.CloseAsync();
return iRes;
}
catch
{
throw;
}
finally
{
if (cmd.Transaction == null)
{
await this.CloseAsync();
}
}
}
/// <summary>
/// 执行查询语句,单行
/// </summary>
/// <param name="sql">执行语句</param>
/// <returns>DbDataReader对象</returns>
public async Task<IDataReader> GetDataReader(string sql)
{
return await GetDataReader(sql, null);
}
/// <summary>
/// 执行查询语句,单行
/// </summary>
/// <param name="sql">执行语句</param>
/// <param name="commandType">执行命令类型</param>
/// <param name="parameters">参数数组</param>
/// <returns>DbDataReader对象</returns>
public async Task<IDataReader> GetDataReader(string sql, DbParameter[] parameters)
{
DbCommand cmd = await CreateDbCommand(sql, parameters);
try
{
IDataReader reader = await cmd.ExecuteReaderAsync(CommandBehavior.SingleRow);
if (cmd.Transaction != null)
{
await cmd.Transaction.CommitAsync();
}
await this.CloseAsync();
return reader;
}
catch
{
cmd.Dispose();
throw;
}
finally
{
if (cmd.Transaction == null)
{
await this.CloseAsync();
}
}
}
/// <summary>
/// 执行查询语句,返回一个包含查询结果的DataTable
/// </summary>
/// <param name="sql">执行语句</param>
/// <returns>DataTable</returns>
public async Task<DataTable> GetDataTable(string sql)
{
return await GetDataTable(sql, null);
}
/// <summary>
/// 执行查询语句,返回一个包含查询结果的DataTable
/// </summary>
/// <param name="sql">执行语句</param>
/// <param name="parameters">参数数组</param>
/// <returns><see cref="DataTable"</returns>
public async Task<DataTable> GetDataTable(string sql, DbParameter[] parameters)
{
using DbCommand cmd = await CreateDbCommand(sql, parameters);
using IDataReader reader = await cmd.ExecuteReaderAsync();
try
{
DataTable dt = reader.GetSchemaTable();
object[] drs = new object[reader.FieldCount];
dt.BeginLoadData();
while (reader.Read())
{
reader.GetValues(drs);
dt.Rows.Add(drs);
}
dt.EndLoadData();
if (cmd.Transaction != null)
{
await cmd.Transaction.CommitAsync();
}
await this.CloseAsync();
return dt;
}
catch
{
throw;
}
finally
{
if (cmd.Transaction == null)
{
await this.CloseAsync();
}
}
}
/// <summary>
/// 执行一个查询语句,返回查询结果的首行首列
/// </summary>
/// <param name="sql">执行语句</param>
/// <returns>首行首列</returns>
public async Task<object> GetScalar(string sql)
{
return await GetScalar(sql, null);
}
/// <summary>
/// 执行一个查询语句,返回查询结果的首行首列
/// </summary>
/// <param name="sql">执行语句</param>
/// <param name="parameters">参数数组</param>
/// <returns>首行首列object</returns>
public async Task<object> GetScalar(string sql, DbParameter[] parameters)
{
using DbCommand cmd = await CreateDbCommand(sql, parameters);
try
{
object obj = await cmd.ExecuteScalarAsync();
if (cmd.Transaction != null)
{
await cmd.Transaction.CommitAsync();
}
await this.CloseAsync();
return obj;
}
catch
{
throw;
}
finally
{
if (cmd.Transaction == null)
{
await this.CloseAsync();
}
}
}
/// <summary>
/// 释放上下文对象
/// </summary>
/// <returns></returns>
#pragma warning disable CA1822 // 将成员标记为 static
private async ValueTask CloseAsync()
#pragma warning restore CA1822 // 将成员标记为 static
{
await _dbContext.DisposeAsync();
}
}
}<file_sep>/src/WebApiCore/CustomClass/CustomExceptionFilter.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
namespace Ligy.Project.WebApi.CustomClass
{
public class CustomExceptionFilterAttribute : Attribute, IExceptionFilter
{
private ILogger<CustomExceptionFilterAttribute> _ilogger = null;
public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> ilogger)
{
_ilogger = ilogger;
}
public void OnException(ExceptionContext context)
{
var sLog = $"【Source】:{context.Exception.TargetSite}\r\n" +
$"【StackTrace】:{context.Exception.StackTrace}\r\n" +
$"【ErrorMessage】:{context.Exception.Message}\r\n";
_ilogger.LogError(sLog);
context.ExceptionHandled = true;
context.Result = new ObjectResult(
new ResultModel(
code: 500,
message: context.Exception.Message,
result: string.Empty,
returnStatus: ReturnStatus.Error
)
);
}
}
}
<file_sep>/src/WebApiCore.IdGenerator/IdGeneratorHelper.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace WebApiCore.IdGenerator
{
/// <summary>
/// ID生成帮助类
/// </summary>
public class IdGeneratorHelper
{
private Snowflake snowflake;
private IdGeneratorHelper()
{
snowflake = new Snowflake(2, 0, 0);
}
public static IdGeneratorHelper Instance { get; } = new IdGeneratorHelper();
/// <summary>
/// 获取分布式唯一Id
/// </summary>
/// <returns></returns>
public long GetId()
{
return snowflake.NextId();
}
}
}
<file_sep>/src/WebApiCore/Startup.cs
using Autofac;
using Ligy.Project.WebApi.CustomClass;
using WebApiCore.Utils;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using WebApiCore.Utils.Model;
namespace Ligy.Project.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddControllersAsServices();
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc("V1", new Microsoft.OpenApi.Models.OpenApiInfo()
{
Version = "Ver 1",
Title = "Ligy WebApi",
});
});
//自定义特性
services.AddMvc(option =>
{
option.Filters.Add<CustomExceptionFilterAttribute>();
option.Filters.Add<CustomResourceFilterAttribute>();
option.Filters.Add<CustomActionAndResultFilter>();
});
services.AddCors(option =>
{
option.AddPolicy("AllowCors", builder =>
{
builder.AllowAnyOrigin().AllowAnyMethod();
});
});
GlobalInvariant.SystemConfig = Configuration.GetSection("SystemConfig").Get<SystemConfig>();
}
/// <summary>
/// 依赖注入Autofac
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule<CustomAutofacModule>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(option =>
{
option.SwaggerEndpoint("/swagger/V1/swagger.json", "Ligy.Project.WebApi");
});
app.UseRouting();
//跨域 必须在UseRouting之后,UseAuthorization之前
app.UseCors("AllowCors");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/src/WebApiCore.Entity/DbCommandCustomInterceptor.cs
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace WebApiCore.EF
{
/// <summary>
/// 自定义数据库拦截器
/// </summary>
internal class DbCommandCustomInterceptor : DbCommandInterceptor
{
//重写拦截方式
}
}<file_sep>/src/WebApiCore.EF/BlogInfos/Blog.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace WebApiCore.Entity.BlogInfos
{
[Table("t_sys_blog")]
public class Blog :BaseEntity
{
public string Url { get; set; }
public BlogType BlogType { get; set; }
public List<Post> Posts { get; set; }
}
public enum BlogType
{
CSDN = 0,
MSDN = 1
}
}
<file_sep>/src/WebApiCore.Entity/DataBase/MySqlDB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApiCore.EF.DataBase
{
/// <summary>
/// MySql数据库
/// </summary>
internal class MySqlDB : BaseDatabase
{
internal MySqlDB(string provider, string connStr) : base(provider, connStr)
{
}
/*----------------------------------------------重写基类默认的sql行为---------------------------------------------------*/
}
}
<file_sep>/src/ApiUnitTest/UnitTest1.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using WebApiCore.EF;
using WebApiCore.EF.DataBase;
using WebApiCore.Entity.BlogInfos;
namespace ApiUnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public IDataBaseOperation GetInterface()
{
return InitDB.Create("SqlServer","Data Source=.;DataBase=MyBlog;Trusted_Connection=True;")
.GetIDataBaseOperation();
}
[TestMethod]
public async Task Insert()
{
}
[TestMethod]
public async Task Delete()
{
}
private readonly Blog blog = new Blog() { Id = 29 };
[TestMethod]
public async Task DeleteById()
{
}
}
}
<file_sep>/src/WebApiCore.Interface/IBlogService.cs
using System;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using WebApiCore.Entity.BlogInfos;
namespace WebApiCore.Interface
{
public interface IBlogService
{
Task<IEnumerable<Blog>> GetBlogs();
}
}
<file_sep>/src/WebApiCore.Entity/DataBase/IDataBaseOperation.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace WebApiCore.EF.DataBase
{
/// <summary>
/// 数据库操作
/// </summary>
public interface IDataBaseOperation
{
#region Property
/// <summary>
/// 数据库当前上下文
/// </summary>
public DbContext DbContext { get; }
/// <summary>
/// 数据库当前上下文事务
/// </summary>
public IDbContextTransaction DbContextTransaction { get; }
#endregion
#region DataBase Methods
/// <summary>
/// 获取当前数据库类型操作
/// </summary>
/// <returns><see cref="IDataBaseOperation"/></returns>
IDataBaseOperation GetIDataBaseOperation();
/// <summary>
/// 确保数据库被删除
/// </summary>
/// <returns><see cref="IDataBaseOperation"/></returns>
Task<IDataBaseOperation> EnsureDeletedAsync();
/// <summary>
/// 确保数据库被创建
/// </summary>
/// <returns><see cref="IDataBaseOperation"/></returns>
Task<IDataBaseOperation> EnsureCreatedAsync();
/// <summary>
/// 开始事务
/// </summary>
/// <returns><see cref="IDataBaseOperation"/></returns>
Task<IDataBaseOperation> BeginTransAsync();
/// <summary>
/// 提交事务
/// </summary>
/// <returns>影响行数<see cref="int"/></returns>
Task<int> CommitTransAsync();
/// <summary>
/// 回滚事务
/// </summary>
/// <returns><see cref="Task"/></returns>
Task RollbackTransAsync();
/// <summary>
/// 回滚事务到保存点
/// </summary>
/// <param name="name">保存点名称</param>
/// <returns><see cref="Task"/></returns>
Task RollbackToSavepointAsync(string name);
/// <summary>
/// 创建事务保存点
/// </summary>
/// <param name="name">保存点名称</param>
/// <returns><see cref="IDataBaseOperation"/></returns>
Task<IDataBaseOperation> CreateSavepointAsync(string name);
/// <summary>
/// 关闭当前数据库上下文对象,并且释放
/// </summary>
/// <returns><see cref="Task"/></returns>
Task CloseAsync();
#endregion
#region T-SQL
Task<int> ExecuteSqlRawAsync(string strSql);
Task<int> ExecuteSqlRawAsync(string strSql, params DbParameter[] dbParameter);
Task<int> ExecuteSqlInterpolatedAsync(FormattableString strSql);
Task<int> ExecuteByProcAsync(string procName);
Task<int> ExecuteByProcAsync(string procName, DbParameter[] dbParameter);
#endregion
#region Insert
Task<int> InsertAsync<T>(T entity) where T : class;
Task<int> InsertAsync(params object[] entities);
Task<int> InsertAsync<T>(IEnumerable<T> entities) where T : class;
#endregion
#region Update
Task<int> UpdateAsync<T>(IEnumerable<T> entities) where T : class;
Task<int> UpdateAllFieldAsync<T>(T entity) where T : class;
#endregion
#region Delete
Task<int> DeleteAsync<T>(T entity) where T : class;
Task<int> DeleteAsync<T>(IEnumerable<T> entities) where T : class;
Task<int> DeleteAsync<T>(int id) where T : class;
Task<int> DeleteAsync<T>(IEnumerable<int> id) where T : class;
#endregion
#region Find
#region EF Find
#region Find Single
Task<T> FindEntityAsync<T>(object KeyValue) where T : class;
Task<T> FindEntityAsync<T>(Expression<Func<T, bool>> condition) where T : class, new();
#endregion
#region Find Entities
Task<IEnumerable<T>> FindListAsync<T>() where T : class, new();
Task<IEnumerable<T>> FindListAsync<T>(Expression<Func<T, bool>> predicate) where T : class, new();
Task<IEnumerable<T>> FindListASCAsync<T>(Expression<Func<T, object>> predicate) where T : class, new();
Task<IEnumerable<T>> FindListDESCAsync<T>(Expression<Func<T, object>> predicate) where T : class, new();
#endregion
#region Pagination
Task<(int total, IEnumerable<T> list)> FindListAsync<T>(string sort, bool isAsc, int pageSize, int pageIndex) where T : class, new();
Task<(int total, IEnumerable<T> list)> FindListAsync<T>(Expression<Func<T, bool>> condition, string sort, bool isAsc, int pageSize, int pageIndex) where T : class, new();
#endregion
#endregion
#region T-SQL Find
#region Find DataTable
Task<DataTable> FindTableAsync(string strSql);
Task<DataTable> FindTableAsync(string strSql, DbParameter[] dbParameter);
#endregion
#region Find Object
Task<object> FindObjectAsync(string strSql);
Task<object> FindObjectAsync(string strSql, DbParameter[] dbParameter);
#endregion
#endregion
#endregion
#region IQueryable
IQueryable<T> IQueryableAsync<T>(Expression<Func<T, bool>> condition) where T : class, new();
#endregion
}
}
<file_sep>/src/WebApiCore.Utils/GlobalInvariant.cs
using System;
using System.Collections.Generic;
using System.Text;
using WebApiCore.Utils.Model;
namespace WebApiCore.Utils
{
public class GlobalInvariant
{
public static SystemConfig SystemConfig { get; set; }
}
}
<file_sep>/src/WebApiCore.EF/BlogInfos/Post.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace WebApiCore.Entity.BlogInfos
{
[Table("t_sys_post")]
public class Post:BaseEntity
{
public string Title { get; set; }
public string Content { get; set; }
public DateTime EditTime { get; set; }
public Blog Blog { get; set; }
}
}
<file_sep>/src/WebApiCore.Entity/MyDbContext.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using WebApiCore.Entity;
namespace WebApiCore.EF
{
public sealed class MyDbContext : DbContext, IDisposable
{
//依赖注入则将OnConfiguring方法添加到Startup的ConfigureServices
//public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
//{
//}
private readonly string _provider;
private readonly string _connStr;
public MyDbContext(string provider, string connStr)
{
this._provider = provider;
this._connStr = connStr;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (this._provider.Equals("SqlServer", StringComparison.OrdinalIgnoreCase))
{
optionsBuilder.UseSqlServer(this._connStr, x => x.CommandTimeout(5));
}
else if (this._provider.Equals("MySql", StringComparison.OrdinalIgnoreCase))
{
//optionsBuilder.(GlobalInvariant.SystemConfig.DBConfig.MySqlConnectionString);
throw new NotImplementedException("MySql尚未实现!");
}
else
throw new NotImplementedException("未知的数据引擎");
optionsBuilder.AddInterceptors(new DbCommandCustomInterceptor());
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Assembly entityAssembly = Assembly.Load(new AssemblyName("WebApiCore.Entity"));
IEnumerable<Type> typesToRegister = entityAssembly.GetTypes().Where(p => !string.IsNullOrEmpty(p.Namespace))
.Where(p => !string.IsNullOrEmpty(p.GetCustomAttribute<TableAttribute>()?.Name))
.Where(p => p.IsSubclassOf(typeof(BaseEntity)));
foreach (Type type in typesToRegister)
{
if (modelBuilder.Model.GetEntityTypes().Any(x => x.Name == type.FullName))
{
continue;
}
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Model.AddEntityType(type);
}
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
string currentTableName = modelBuilder.Entity(entity.Name).Metadata.GetTableName();
modelBuilder.Entity(entity.Name).ToTable(currentTableName);
modelBuilder.Entity(entity.Name)
.Property("Id");
}
base.OnModelCreating(modelBuilder);
}
}
}
|
ef417d784ec0cac5635e2f9fc41a40a75710ddcf
|
[
"C#"
] | 31 |
C#
|
CheneyChenStar/CoreBlog
|
69523f0909954abb992297bce9a3c5478de9ccb9
|
5f26a0d42cf7c265590ffae21e2bfe9e36efde13
|
refs/heads/master
|
<repo_name>aldohardiansyah/AuroraApp<file_sep>/src/assets/icon/index.js
import splash1 from './splash-1.png';
import splash2 from './splash-2.png';
export { splash1, splash2 };
<file_sep>/src/pages/Splash/index.js
import React, { useEffect } from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import { splash2 } from '../../assets';
const Splash = ({ navigation }) => {
// useEffect(() => {
// setTimeout(() => {
// navigation.replace('MainApp');
// }, 3000);
// }, [navigation]);
return (
<View
style={{
backgroundColor: '#8977b5',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Image source={splash2} style={styles.logo} />
<Text style={styles.text}>Write down your precious Idea</Text>
</View>
);
};
export default Splash;
const styles = StyleSheet.create({
logo: {
width: 75,
height: 75,
marginBottom: 20,
},
text: {
color: 'white',
},
});
|
f9cd59328dcc1c58e23e979b0b28c9c9fb9fbf1a
|
[
"JavaScript"
] | 2 |
JavaScript
|
aldohardiansyah/AuroraApp
|
9c389034241de9afcb5dd15681bb3f343ad38cc6
|
c493189089994cb7a8cf4d8cdb4a3c216c5936c4
|
refs/heads/main
|
<repo_name>tmdwo5811/leanTypeScript<file_sep>/README.md
# leanTypeScript
타입 스크립트 연습
|
e3f3f9716bb8aa801582ee71786e5e319b5257b8
|
[
"Markdown"
] | 1 |
Markdown
|
tmdwo5811/leanTypeScript
|
adac7616b8766c7141ad7b0727d9dad317a11d99
|
867da0d4ab6572f58abbc1d8690db0222a17ede7
|
refs/heads/master
|
<repo_name>alfrizzle/MSDS-453<file_sep>/README.md
# MSDS-453
Assignments for MSDS 453: Natural Language Processing
|
7be983d7c37c495da725ccf88a66d2ad5d2fbca0
|
[
"Markdown"
] | 1 |
Markdown
|
alfrizzle/MSDS-453
|
10fc35a362558978dd6fb3efb22759f84635fa54
|
381186c55a51e805a7ffa8ab38e53facf9c7cfb4
|
refs/heads/main
|
<repo_name>jeronrobke/web-contact-form<file_sep>/README.md
# web-contact-form
|
e492a21acb3ed0327f0b13768316ce8648d4302f
|
[
"Markdown"
] | 1 |
Markdown
|
jeronrobke/web-contact-form
|
ac84daf213b8e081ba2851bd3f73e0253d34fc48
|
141dcd0a2779537c947463324cb541ec15ed6f7f
|
refs/heads/master
|
<file_sep>#include <bits/stdc++.h>
using namespace std;
struct Node;
std::deque<Node> cache;
Node* fetch_new() {
cache.emplace_back();
return &cache.back();
}
Node* fetch_new(Node const& node) {
cache.emplace_back(node);
return &cache.back();
}
struct Node {
Node* left = nullptr;
Node* right = nullptr;
long long data = 0;
void build(int l, int r) {
if (l + 1 < r) {
int m = (l + r) / 2;
left = fetch_new();
right = fetch_new();
left->build(l, m);
right->build(m, r);
}
}
Node* set(int pos, int x, int l, int r) {
Node* neww = fetch_new(*this);
if (l + 1 == r) neww->data = x;
else {
int m = (l + r) / 2;
if (pos < m) neww->left = neww->left->set(pos, x, l, m);
else neww->right = neww->right->set(pos, x, m, r);
neww->data = neww->left->data + neww->right->data;
}
return neww;
}
long long qry(int bl, int br, int l, int r) {
if (bl >= r || br <= l) return 0ll;
if (bl <= l && r <= br) return data;
int m = (l + r) / 2;
return left->qry(bl, br, l, m) + right->qry(bl, br, m, r);
}
};
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
auto root = fetch_new();
root->build(0, n);
for(int i = 0; i < n; ++i)
{
long long v;
cin >> v;
auto new_root = root->set(i, v, 0, n);
root = new_root;
}
vector< Node* > heads;
heads.emplace_back(root);
for(int i = 0; i < q; ++i)
{
int t;
cin >> t;
if(t == 1)
{
int k, a; long long x;
cin >> k >> a >> x;
--k; --a;
auto new_head = heads[k]->set(a, x, 0, n);
// aqui que em tese rolou a mudança!
heads[k] = new_head;
}
else if(t == 2)
{
int k, a, b;
cin >> k >> a >> b;
--k; --a; --b;
cout << heads[k]->qry(a, b + 1, 0, n) << '\n';
}
else
{
int k; cin >> k;
heads.emplace_back(fetch_new(*heads[k - 1]));
}
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define TRACE(x) x
#define WATCH(x) TRACE( cout << #x" = " << x << endl)
#define PRINT(x) TRACE(printf(x))
#define WATCHR(a, b) TRACE( for(auto c = a; c != b;) cout << *(c++) << " "; cout << endl)
#define WATCHC(V) TRACE({cout << #V" = "; WATCHR(V.begin(), V.end());})
#define rep(i, a, b) for(int i = (a); (i) < (b); ++(i))
#define trav(a, x) for(auto& a : x)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) static_cast<int>(x.size())
#define mp make_pair
#define fi first
#define se second
using vi = vector<int>;
using vvi = vector<vi>;
using ll = long long;
using vll = vector<ll>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
void buff() { ios::sync_with_stdio(false); cin.tie(nullptr); }
constexpr ll MOD = 1e9 + 7;
inline ll pow_mod(ll a, ll b, ll mod = MOD) {
ll res = 1; a %= mod; assert(b >= 0);
for(;b;b>>=1) {
if(b & 1) res = (res * a) % mod;
a = (a * a) % mod;
}
return res;
}
template<typename T> inline void remin(T& x, const T& y) { x = min(x, y); }
template<typename T> inline void remax(T& x, const T& y) { x = max(x, y); }
template<typename T> ostream& operator<<(ostream &os, const vector<T>& v) {
os << "{"; string sep; for(const auto& x : v) os << sep << x, sep = ", "; return os << "}";
}
template<typename T, size_t size> ostream& operator<<(ostream& os, const array<T, size>& arr) {
os << "{"; string sep; for(const auto& x : arr) os << sep << x, sep = ", "; return os << "}";
}
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) {
return os << '(' << p.first << ", " << p.second << ')';
}
template <typename T> struct seg
{
int N;
vector<T> Tree;
T id;
seg(int n, T dummy) : N(n), id(dummy) { Tree.assign(2 * N, id); }
void build()
{
for (int idx = N - 1; idx > 0; --idx)
Tree[idx] = Tree[(idx << 1)] * Tree[(idx << 1) | 1];
}
void update(int p, T val)
{
Tree[p += N] = val;
while (p > 1)
{
if((p^1) > p) Tree[p >> 1] = Tree[p] * Tree[p ^ 1];
else Tree[p >> 1] = Tree[p^1] * Tree[p];
p >>= 1;
}
}
// Query of [l, r)
T query(int l, int r)
{
T res_r, res_l= id;
for (l += N, r += N; l < r; l >>= 1, r >>= 1)
{
if (l & 1) res_l = res_l * Tree[l++];
if (r & 1) res_r = Tree[--r] * res_r;
}
return res_l * res_r;
}
};
struct node {
ll bp, bo, bs, sum;
node(ll _bp = 0ll, ll _bo = 0ll, ll _bs = 0ll, ll _sum = 0ll) : bp(_bp), bo(_bo), bs(_bs), sum(_sum) {}
node operator* (const node& rhs) const {
// Tenho que ensinar a combinar dois nós!
ll new_best_prefix = max(bp, sum + rhs.bp);
ll new_best_suffix = max(rhs.bs, rhs.sum + bs);
ll new_best_overall = max(bo, max(rhs.bo, bs + rhs.bp));
ll new_sum = sum + rhs.sum;
return node(new_best_prefix, new_best_overall, new_best_suffix, new_sum);
}
};
int main()
{
buff();
int n, m;
cin >> n >> m;
auto S = seg<node>(n, node());
for(int i = 0; i < n; ++i)
{
ll x;
cin >> x;
S.Tree[n + i] = node(x, x, x, x);
}
S.build();
for(int i = 0; i < m; ++i)
{
int k; ll x;
cin >> k >> x;
--k;
S.update(k, node(max(0ll, x), max(0ll, x), max(0ll, x), x));
auto res = S.query(0, n);
cout << res.bo << endl;
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define TRACE(x) x
#define WATCH(x) TRACE( cout << #x" = " << x << endl)
#define PRINT(x) TRACE(printf(x))
#define WATCHR(a, b) TRACE( for(auto c = a; c != b;) cout << *(c++) << " "; cout << endl)
#define WATCHC(V) TRACE({cout << #V" = "; WATCHR(V.begin(), V.end());})
#define rep(i, a, b) for(int i = (a); (i) < (b); ++(i))
#define trav(a, x) for(auto& a : x)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) static_cast<int>(x.size())
#define mp make_pair
#define fi first
#define se second
using vi = vector<int>;
using vvi = vector<vi>;
using ll = long long;
using vll = vector<ll>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
void buff() { ios::sync_with_stdio(false); cin.tie(nullptr); }
constexpr ll MOD = 1e9 + 7;
inline ll pow_mod(ll a, ll b, ll mod = MOD) {
ll res = 1; a %= mod; assert(b >= 0);
for(;b;b>>=1) {
if(b & 1) res = (res * a) % mod;
a = (a * a) % mod;
}
return res;
}
template<typename T> inline void remin(T& x, const T& y) { x = min(x, y); }
template<typename T> inline void remax(T& x, const T& y) { x = max(x, y); }
template<typename T> ostream& operator<<(ostream &os, const vector<T>& v) {
os << "{"; string sep; for(const auto& x : v) os << sep << x, sep = ", "; return os << "}";
}
template<typename T, size_t size> ostream& operator<<(ostream& os, const array<T, size>& arr) {
os << "{"; string sep; for(const auto& x : arr) os << sep << x, sep = ", "; return os << "}";
}
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) {
return os << '(' << p.first << ", " << p.second << ')';
}
inline int64_t gilbert_order(int x, int y, int pow, int rotate) {
if (pow == 0) {
return 0;
}
int hpow = 1 << (pow-1);
int seg = (x < hpow) ? (
(y < hpow) ? 0 : 3
) : (
(y < hpow) ? 1 : 2
);
seg = (seg + rotate) & 3;
const int rotateDelta[4] = {3, 0, 0, 1};
int nx = x & (x ^ hpow), ny = y & (y ^ hpow);
int nrot = (rotate + rotateDelta[seg]) & 3;
int64_t subSquareSize = int64_t(1) << (2*pow - 2);
int64_t ans = seg * subSquareSize;
int64_t add = gilbert_order(nx, ny, pow-1, nrot);
ans += (seg == 1 || seg == 2) ? add : (subSquareSize - add - 1);
return ans;
}
struct query {
int l, r, i;
int64_t ord;
query(int l, int r, int i) : l(l), r(r), i(i) {
ord = gilbert_order(l, r, 19, 0);
}
};
inline bool operator<(const query& a, const query& b) {
return a.ord < b.ord;
}
constexpr int ms = 2e5 + 13;
int f[ms];
int main() {
buff();
int n, m;
cin >> n >> m;
vector<int> v(n), cpy;
for(int i = 0; i < n; ++i) {
cin >> v[i];
cpy.push_back(v[i]);
}
sort(all(cpy));
cpy.erase(unique(all(cpy)), cpy.end());
for(int i = 0; i < n; ++i) {
v[i] = (int) (lower_bound(all(cpy), v[i]) - cpy.begin());
}
vector< query > q;
for(int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y; --x; --y;
q.push_back(query(x, y, i));
}
sort(all(q));
int l = 0, r = 0;
vector<int> ans(m, 0);
int cur_val = 0;
auto add = [&] (int id) {
f[v[id]]++;
if(f[v[id]] == 1) cur_val++;
};
auto remove = [&] (int id) {
f[v[id]]--;
if(f[v[id]] == 0) cur_val--;
};
add(0);
for(const auto& qry : q) {
while(l < qry.l) {
remove(l);
++l;
}
while(l > qry.l) {
--l;
add(l);
}
while(r < qry.r) {
++r;
add(r);
}
while(r > qry.r) {
remove(r);
r--;
}
ans[qry.i] = cur_val;
}
for(const auto& val : ans) cout << val << endl;
return 0;
}<file_sep>#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef tree<
pair<int, int>,
null_type,
less< pair<int, int>>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n;
cin >> n;
vector<int> v(n);
ordered_set SET;
for(int i = 0; i < n; ++i) {
int x;
cin >> x;
SET.insert({i, x});
}
for(int i = 0; i < n; ++i) {
int x;
cin >> x;
--x;
auto vamo = SET.find_by_order(x);
cout << vamo->second << " ";
SET.erase(vamo);
}
cout << '\n';
return 0;
}<file_sep># CSES Solutions
This repository contains my solutions to the CSES problemset (https://cses.fi/problemset/list/).
<file_sep>#include <bits/stdc++.h>
#define all(v) (v).begin(), (v).end()
using namespace std;
using ll = long long;
/* Lazy segtree.
Garantir que:
1 - Combinar nós é uma operação associativa
2 - Updates são comutativos
*/
constexpr long long ms = 2e5 + 13;
long long n;
struct node {
long long S, lz, lz2;
node(ll _S = 0ll, ll _lz = 0ll, ll _lz2 = 0ll) : S(_S), lz(_lz), lz2(_lz2) {}
} st[4 * ms];
node combine(const node& L, const node& R) {
return node(L.S + R.S);
}
void build(const vector<node>& leaves, long long pos = 1ll, long long tl = 0, long long tr = n - 1) {
if(tl == tr) st[pos] = leaves[tl];
else {
long long tm = (tl + tr) / 2;
build(leaves, pos * 2, tl, tm);
build(leaves, pos * 2 + 1, tm + 1, tr);
st[pos] = combine(st[pos * 2], st[pos * 2 + 1]);
}
}
void app(long long pos, long long x1, long long x2, long long l2, long long r2)
{
st[pos].S += x1 * (r2 - l2 + 1);
long long soma_pa = (r2 * (r2 + 1ll ) ) / 2ll - ( l2 * (l2 - 1ll) ) / 2ll;
st[pos].S += soma_pa * x2;
st[pos].lz += x1;
st[pos].lz2 += x2;
}
void push(long long pos, long long l2, long long m2, long long r2) {
app(2 * pos, st[pos].lz, st[pos].lz2, l2, m2);
app(2 * pos + 1, st[pos].lz, st[pos].lz2, m2 + 1, r2);
st[pos].lz = st[pos].lz2 = 0;
}
void upd(long long l1, long long r1, long long x, long long x2, long long i = 1, long long l2 = 0, long long r2 = n - 1)
{
if(l1 <= l2 && r2 <= r1) {
app(i, x, x2, l2, r2);
return;
}
long long m2 = (l2 + r2) / 2ll;
push(i, l2, m2, r2);
if(l1 <= m2) upd(l1, r1, x, x2, 2 * i, l2, m2);
if(m2 < r1) upd(l1, r1, x, x2, 2 * i + 1, m2 + 1, r2);
st[i].S = st[2 * i].S + st[2 * i + 1].S;
}
long long query(long long l1, long long r1, long long i = 1, long long l2 = 0, long long r2 = n - 1)
{
if(l1 <= l2 && r2 <= r1) return st[i].S;
int m2 = (l2 + r2) / 2ll;
push(i, l2, m2, r2);
long long ret = 0ll;
if(l1 <= m2) ret += query(l1, r1, 2 * i, l2, m2);
if(m2 < r1) ret += query(l1, r1, 2 * i + 1, m2 + 1, r2);
return ret;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int q;
cin >> n >> q;
vector< node > leaves(n);
for(int i = 0; i < n; ++i) cin >> leaves[i].S;
build(leaves);
for(int i = 0; i < q; ++i)
{
int t, a, b;
cin >> t >> a >> b, --a, --b;
if(t == 1) {
upd(a, b, 1 - a, 1);
}
else {
cout << query(a, b) << endl;
}
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
constexpr int bs = 500;
constexpr long long inf = 0x3f3f3f3fLL;
int n, q;
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
cin >> n >> q;
vector< long long > price(n);
for(auto& p : price) cin >> p;
vector< long long > cheap_left(bs, -1), cheap_right(bs, -1);
for(long long i = 0; i < n; ++i)
{
int block_num = i / bs;
long long left_dist = i + price[i];
if(cheap_left[block_num] == -1) cheap_left[block_num] = i;
else if(left_dist < price[cheap_left[block_num]] + cheap_left[block_num]) cheap_left[block_num]= i;
long long right_dist = (n - i) + price[i];
if(cheap_right[block_num] == -1) cheap_right[block_num] = i;
else if(right_dist < price[cheap_right[block_num]] + (n - cheap_right[block_num])) cheap_right[block_num] = i;
}
auto update_block = [&] (int b_idx)
{
int st = b_idx * bs;
int nd = min(n, st + bs);
cheap_left[b_idx] = cheap_right[b_idx] = -1;
for(int i = st; i < nd; ++i)
{
long long left_dist = i + price[i];
if(cheap_left[b_idx] == -1) cheap_left[b_idx] = i;
else if(left_dist < price[cheap_left[b_idx]] + cheap_left[b_idx]) cheap_left[b_idx]= i;
long long right_dist = (n - i) + price[i];
if(cheap_right[b_idx] == -1) cheap_right[b_idx] = i;
else if(right_dist < price[cheap_right[b_idx]] + (n - cheap_right[b_idx])) cheap_right[b_idx] = i;
}
};
auto solve = [&] (int idx)
{
int b_idx = idx / bs;
int st = b_idx * bs;
int nd = min(n, st + bs);
long long ans = inf;
for(int i = st; i < nd; ++i)
{
long long d = abs(i - idx) + price[i];
ans = min(ans, d);
}
for(int b = 0; b < bs; ++b)
{
if(b == b_idx || b * bs >= n) continue;
if(b < b_idx)
{
long long d = price[cheap_right[b]] + (idx - cheap_right[b]);
ans = min(ans, d);
}
else
{
long long d = price[cheap_left[b]] + (cheap_left[b] - idx);
ans = min(ans, d);
}
}
return ans;
};
for(int i = 0; i < q; ++i)
{
int t;
cin >> t;
if(t == 1)
{
int k; long long x;
cin >> k >> x;
// change of price
--k;
price[k] = x;
update_block(k / bs);
}
else
{
int pos; cin >> pos;
cout << solve(pos - 1) << '\n';
}
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
template<typename T>
struct segment_tree {
int n;
T id;
vector<T> tree;
segment_tree(int sz, T _id) : n(sz), id(_id) {
tree.assign(4 * n, id);
}
T combine(const T& a, const T& b) {
return max(a, b);
}
void build(int L, int R, int index, const vector<T>& leaves) {
if(L == R) tree[index] = leaves[L];
else {
int mid = (L + R) / 2;
int left_kid = index * 2 + 1;
int right_kid = index * 2 + 2;
build(L, mid, left_kid, leaves);
build(mid + 1, R, right_kid, leaves);
tree[index] = combine(tree[left_kid], tree[right_kid]);
}
}
void build(const vector<T>& leaves) {
assert(static_cast<int>(leaves.size()) == n);
build(0, n - 1, 0, leaves);
}
void update(int L, int R, int index, int upd_id, const T new_val) {
if(L == R) tree[index] += new_val;
else {
int mid = (L + R) / 2;
int left_kid = index * 2 + 1;
int right_kid = index * 2 + 2;
if(upd_id <= mid) update(L, mid, left_kid, upd_id, new_val);
else update(mid + 1, R, right_kid, upd_id, new_val);
tree[index] = combine(tree[left_kid], tree[right_kid]);
}
}
void update(int pos, const T new_val) {
update(0, n - 1, 0, pos, new_val);
}
T query(int L, int R, int index, int query_l, int query_r) {
if(L > query_r || R < query_l) return id;
if(L >= query_l && R <= query_r) return tree[index];
int mid = (L + R) / 2;
int left_kid = index * 2 + 1;
int right_kid = index * 2 + 2;
T QL = query(L, mid, left_kid, query_l, query_r);
T QR = query(mid + 1, R, right_kid, query_l, query_r);
return combine(QL, QR);
}
T query(int l, int r) { return query(0, n - 1, 0, l, r); }
int assign_room(int val) {
if(tree[0] < val) return 0; // nao tem nenhum quarto do tamanho desejado!
int lft = 0, rht = n - 1;
int cur_id = 0;
while(lft != rht) {
int left_kid = cur_id * 2 + 1;
int right_kid = cur_id * 2 + 2;
int mid = (lft + rht) / 2;
if(tree[left_kid] < val) {
lft = mid + 1;
cur_id = right_kid;
}
else {
rht = mid;
cur_id = left_kid;
}
}
return lft + 1;
}
};
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q;
cin >> n >> q;
vector<int> leaves(n);
for(auto& x : leaves) cin >> x;
auto seg = segment_tree<int>(n, 0);
seg.build(leaves);
for(int i = 0; i < q; ++i)
{
int qnt;
cin >> qnt;
int v = seg.assign_room(qnt);
cout << v << " ";
if(v > 0) {
seg.update((v - 1), -qnt);
}
}
cout << '\n';
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define TRACE(x) x
#define WATCH(x) TRACE( cout << #x" = " << x << endl)
#define PRINT(x) TRACE(printf(x))
#define WATCHR(a, b) TRACE( for(auto c = a; c != b;) cout << *(c++) << " "; cout << endl)
#define WATCHC(V) TRACE({cout << #V" = "; WATCHR(V.begin(), V.end());})
#define rep(i, a, b) for(int i = (a); (i) < (b); ++(i))
#define trav(a, x) for(auto& a : x)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) static_cast<int>(x.size())
#define mp make_pair
#define fi first
#define se second
using vi = vector<int>;
using vvi = vector<vi>;
using ll = long long;
using vll = vector<ll>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
void buff() { ios::sync_with_stdio(false); cin.tie(nullptr); }
constexpr ll MOD = 1e9 + 7;
inline ll pow_mod(ll a, ll b, ll mod = MOD) {
ll res = 1; a %= mod; assert(b >= 0);
for(;b;b>>=1) {
if(b & 1) res = (res * a) % mod;
a = (a * a) % mod;
}
return res;
}
template<typename T> inline void remin(T& x, const T& y) { x = min(x, y); }
template<typename T> inline void remax(T& x, const T& y) { x = max(x, y); }
template<typename T> ostream& operator<<(ostream &os, const vector<T>& v) {
os << "{"; string sep; for(const auto& x : v) os << sep << x, sep = ", "; return os << "}";
}
template<typename T, size_t size> ostream& operator<<(ostream& os, const array<T, size>& arr) {
os << "{"; string sep; for(const auto& x : arr) os << sep << x, sep = ", "; return os << "}";
}
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) {
return os << '(' << p.first << ", " << p.second << ')';
}
struct item {
pair<int, int> key;
int prior, cnt;
item * l, * r;
item() { }
item (pair<int, int> key, int prior) : key(key), prior(prior), cnt(1), l(NULL), r(NULL) { }
};
typedef item * pitem;
inline int cnt (pitem t) {
return t ? t->cnt : 0;
}
inline void upd_cnt (pitem t) {
if (t) t->cnt = 1 + cnt(t->l) + cnt(t->r);
}
void split (pitem t, pair<int, int> key, pitem & l, pitem & r) {
if (!t)
l = r = NULL;
else if (key < t->key)
split (t->l, key, l, t->l), r = t;
else
split (t->r, key, t->r, r), l = t;
upd_cnt(t);
}
void insert (pitem & t, pitem it) {
if (!t)
t = it;
else if (it->prior > t->prior)
split (t, it->key, it->l, it->r), t = it;
else
insert (it->key < t->key ? t->l : t->r, it);
upd_cnt(t);
}
void merge (pitem & t, pitem l, pitem r) {
if (!l || !r)
t = l ? l : r;
else if (l->prior > r->prior)
merge (l->r, l->r, r), t = l;
else
merge (r->l, l, r->l), t = r;
upd_cnt(t);
}
void erase (pitem & t, pair<int, int> key) {
if (t->key == key) {
pitem th = t;
merge (t, t->l, t->r);
delete th;
}
else
erase (key < t->key ? t->l : t->r, key);
upd_cnt(t);
}
pitem unite (pitem l, pitem r) {
if (!l || !r) return l ? l : r;
if (l->prior < r->prior) swap (l, r);
pitem lt, rt;
split (r, l->key, lt, rt);
l->l = unite (l->l, lt);
l->r = unite (l->r, rt);
return l;
}
int n, q, x, y;
char c;
int main() {
buff();
pitem root = nullptr;
cin >> n >> q;
vector<int> sal(n);
for(int i = 0; i < n; ++i) {
cin >> sal[i];
pitem cur = new item(make_pair(sal[i], i), rand() - 1);
insert(root, cur);
}
// agora tenho que resolver as queries
for(int i = 0; i < q; ++i)
{
cin >> c >> x >> y;
if(c == '?')
{
pair<int, int> grande = {y + 1, -1};
int ans = 0;
pitem L, R;
split(root, grande, L, R);
ans += (L ? L->cnt : 0);
merge(root, L, R);
grande.first = x;
split(root, grande, L, R);
ans -= (L ? L->cnt : 0);
merge(root, L, R);
cout << ans << '\n';
}
else {
int id = x - 1;
erase(root, make_pair(sal[id], id));
sal[id] = y;
pitem cur = new item(make_pair(sal[id], id), rand() - 1);
insert(root, cur);
}
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
template<typename T>
struct segment_tree {
int n;
T id;
vector<T> tree;
segment_tree(int sz, T _id) : n(sz), id(_id) {
tree.assign(4 * n, id);
}
T combine(const T& a, const T& b) {
return a + b;
}
void build(int L, int R, int index, const vector<T>& leaves) {
if(L == R) tree[index] = leaves[L];
else {
int mid = (L + R) / 2;
int left_kid = index * 2 + 1;
int right_kid = index * 2 + 2;
build(L, mid, left_kid, leaves);
build(mid + 1, R, right_kid, leaves);
tree[index] = combine(tree[left_kid], tree[right_kid]);
}
}
void build(const vector<T>& leaves) {
assert(static_cast<int>(leaves.size()) == n);
build(0, n - 1, 0, leaves);
}
void update(int L, int R, int index, int upd_id, const T new_val) {
if(L == R) tree[index] = new_val;
else {
int mid = (L + R) / 2;
int left_kid = index * 2 + 1;
int right_kid = index * 2 + 2;
if(upd_id <= mid) update(L, mid, left_kid, upd_id, new_val);
else update(mid + 1, R, right_kid, upd_id, new_val);
tree[index] = combine(tree[left_kid], tree[right_kid]);
}
}
void update(int pos, const T new_val) {
update(0, n - 1, 0, pos, new_val);
}
T query(int L, int R, int index, int query_l, int query_r) {
if(L > query_r || R < query_l) return id;
if(L >= query_l && R <= query_r) return tree[index];
int mid = (L + R) / 2;
int left_kid = index * 2 + 1;
int right_kid = index * 2 + 2;
T QL = query(L, mid, left_kid, query_l, query_r);
T QR = query(mid + 1, R, right_kid, query_l, query_r);
return combine(QL, QR);
}
T query(int l, int r) { return query(0, n - 1, 0, l, r); }
};
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q;
cin >> n >> q;
vector<long long> leaves(n);
for(auto& x : leaves) cin >> x;
auto seg = segment_tree<long long>(n, 0);
seg.build(leaves);
for(int i = 0; i < q; ++i) {
int t;
cin >> t;
if(t == 1) {
int k, u;
cin >> k >> u;
--k;
seg.update(k, u);
}
else {
int l, r;
cin >> l >> r;
--l; --r;
cout << seg.query(l, r) << '\n';
}
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q;
cin >> n >> q;
vector<long long> v(n);
for(auto& x : v) cin >> x;
vector<long long> p_sum(n);
partial_sum(v.begin(), v.end(), p_sum.begin());
for(int i = 0; i < q; ++i) {
int a, b;
cin >> a >> b;
--a; --b;
cout << p_sum[b] - (a > 0 ? p_sum[a - 1] : 0ll) << '\n';
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
template <typename T> struct BIT2D
{
vector<vector<T>> table;
int n, m;
T id;
BIT2D(int _n, int _m, T _id) : n(_n + 1), m(_m + 1), id(_id)
{
table.assign(n, vector<T>(m));
}
// 0-indexed!
inline void modify(int i, int j, T delta)
{
++i, ++j;
int x = i;
while (x < n)
{
int y = j;
while (y < m)
{
table[x][y] += delta;
y |= (y + 1);
}
x |= (x + 1);
}
}
inline T get(int i, int j)
{
T v = id;
int x = i + 1;
while (x > 0)
{
int y = j + 1;
while (y > 0)
{
v += table[x][y];
y = (y & (y + 1)) - 1;
}
x = (x & (x + 1)) - 1;
}
return v;
}
inline T get(int y1, int x1, int y2, int x2)
{
return get(y2, x2) - get(y1 - 1, x2) - get(y2, x1 - 1) + get(y1 - 1, x1 - 1);
}
};
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q;
cin >> n >> q;
auto B = BIT2D<int>(n + 1, n + 1, 0);
vector< string > mat(n);
for(int i = 0; i < n; ++i)
{
cin >> mat[i];
for(int j = 0; j < n; ++j)
{
if(mat[i][j] == '*') B.modify(i, j, 1);
}
}
for(int i = 0; i < q; ++i)
{
int t;
cin >> t;
if(t == 1)
{
int x, y;
cin >> x >> y;
--x; --y;
if(mat[x][y] == '.')
{
mat[x][y] = '*';
B.modify(x, y, 1);
}
else
{
mat[x][y] = '.';
B.modify(x, y, -1);
}
}
else
{
int y1, x1, y2, x2;
cin >> y1 >> x1 >> y2 >> x2;
--y1; --x1; --y2; --x2;
cout << B.get(y1, x1, y2, x2) << '\n';
}
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
constexpr int ms = 1013;
int mat[ms][ms];
inline int solve(int y1, int x1, int y2, int x2) {
int res = mat[y2][x2] - mat[y1 - 1][x2] - mat[y2][x1 - 1] + mat[y1 - 1][x1 - 1];
return res;
}
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q;
cin >> n >> q;
memset(mat, 0, sizeof mat);
for(int i = 1; i <= n; ++i) {
string s;
cin >> s;
for(int j = 0; j < n; ++j) {
if(s[j] == '*') mat[i][j + 1] = 1;
}
}
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j) {
mat[i][j] += (mat[i - 1][j] + mat[i][j - 1] - mat[i - 1][j - 1]);
}
}
for(int i = 0; i < q; ++i)
{
int a, b, c, d;
cin >> a >> b >> c >> d;
cout << solve(a, b, c, d) << '\n';
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
template <typename T> struct seg_tree
{
int S;
T identity;
vector<T> value;
seg_tree<T>(int _S, T _identity = T())
{
S = _S, identity = _identity;
value.resize(2 * S + 1, identity);
}
void set_leaves(vector<T>& leaves)
{
copy(leaves.begin(), leaves.end(), value.begin() + S);
for (int i = S - 1; i > 0; i--)
value[i] = value[2 * i] * value[2 * i + 1];
}
void upd(int i, T v)
{
i += S;
value[i] = v;
while (i > 1)
{
i /= 2;
value[i] = value[2 * i] * value[2 * i + 1];
}
}
// query is about closed ranges [i, j]
T query(int i, int j)
{
T res_left = identity, res_right = identity;
for (i += S, j += S; i <= j; i /= 2, j /= 2)
{
if ((i & 1) == 1) res_left = res_left * value[i++];
if ((j & 1) == 0) res_right = value[j--] * res_right;
}
return res_left * res_right;
}
};
struct Node {
int len;
long long max_pref, max_suff, full_sum;
Node(int _len = 1, long long _max_pref = 0ll, long long _max_suff = 0ll, long long _full_sum = 0ll) :
len(_len), max_pref(_max_pref), max_suff(_max_suff), full_sum(_full_sum) {}
Node(long long val) {
len = 1;
max_pref = max(0ll, val); max_suff = max(0ll, val);
full_sum = val;
}
Node operator* (const Node& rhs)
{
int new_len = len + rhs.len;
long long m_pref = max(0ll, max(full_sum + rhs.max_pref, max_pref));
long long m_suff = max(0ll, max(rhs.full_sum + max_suff, rhs.max_suff));
long long fs = full_sum + rhs.full_sum;
return Node(new_len, m_pref, m_suff, fs);
}
};
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q;
cin >> n >> q;
vector< Node > V(n);
for(int i = 0; i < n; ++i)
{
V[i].len = 1;
cin >> V[i].full_sum;
V[i].max_pref = max(0ll, V[i].full_sum);
V[i].max_suff = max(0ll, V[i].full_sum);
}
seg_tree<Node> ST(n);
ST.set_leaves(V);
for(int i = 0; i < q; ++i)
{
int t;
cin >> t;
if(t == 1)
{
long long k, u;
cin >> k >> u;
ST.upd(k - 1, Node(u));
}
else
{
int a, b;
cin >> a >> b;
cout << ST.query(a - 1, b - 1).max_pref << '\n';
}
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
constexpr int ms = 2e5 + 13;
const long long INF = 1e18;
int n, q;
long long x[ms], pref[ms], ans[ms], contrib[ms], bit[ms];
vector< pair<int, int> > queries_per_startpoint[ms];
inline void update(int pos, long long val) {
for(; pos <= n; pos += pos & -pos) bit[pos] += val;
}
long long query(int a, int b) {
long long ans = 0;
for(; b; b -= b & -b) ans += bit[b];
for(a--; a; a -= a & -a) ans -= bit[a];
return ans;
}
int main() {
cin.tie(0)->sync_with_stdio(false);
cin >> n >> q;
for(int i = 1; i <= n; ++i) {
cin >> x[i];
pref[i] = pref[i - 1] + x[i];
}
x[n + 1] = INF;
pref[n + 1] = pref[n] + x[n + 1];
for(int i = 0; i < q; ++i)
{
int a, b;
cin >> a >> b;
queries_per_startpoint[a].emplace_back(b, i);
}
deque<int> st = {n + 1};
for(int i = n; i; i--) {
while(!st.empty() && x[i] >= x[st.front()]) {
update(st.front(), - contrib[st.front()]);
st.pop_front();
}
contrib[i] = (st.front() - 1 - i) * x[i] - (pref[st.front() - 1] - pref[i]);
update(i, contrib[i]);
st.push_front(i);
for(pair<int, int>& j : queries_per_startpoint[i]) {
int pos = upper_bound(st.begin(), st.end(), j.first) - st.begin() - 1;
ans[j.second] = (pos ? query(i, st[pos - 1]) : 0) + (j.first - st[pos]) * x[st[pos]] - (pref[j.first] - pref[st[pos]]);
}
}
for(int i = 0; i < q; ++i) cout << ans[i] << '\n';
return 0;
}
|
491a417700909d21b6f0487833f9926da597273d
|
[
"Markdown",
"C++"
] | 15 |
Markdown
|
FranciscoThiesen/cses_solutions
|
72071fc4cd668f61de8cff92e9c1d386b927f104
|
52c9df9398ae0e8036f367615bd35acc3b62f0ec
|
refs/heads/master
|
<repo_name>Jorge241289/Coursera<file_sep>/README.md
# Coursera
Realizando el curso de Coursera
|
b49f789515eb7af87cfac0af390b3002627dec81
|
[
"Markdown"
] | 1 |
Markdown
|
Jorge241289/Coursera
|
2ac43af479a3781db5dc62e65125ff4bfb224082
|
2510c193d62fc979dfdc1171ee9b20de7372a2ca
|
refs/heads/master
|
<file_sep>'use strict';
/** Circular Linkedlist based on SinglyLinkedList **/
var Link = function (key, value){
this.data = { key: key, value: value };
this.next = null;
};
var CircularLinkedList = function () {
this.head = null;
this._length = 0;
};
CircularLinkedList.prototype = {
add: function(key, value) {
var newLink = new Link(key, value),
currentLink = this.head;
if(!currentLink) {
this.head = newLink;
this.head.next = this.head;
this._length++;
return newLink;
}
//Traverse to the last link
while(currentLink.next !== this.head) {
currentLink = currentLink.next;
}
//Set next pointer to new link.
currentLink.next = newLink;
//Set next pointer of new link to head to make circular.
newLink.next = this.head;
//Increment length
this._length++;
return newLink;
},
reverse: function() {
if(this._length <= 1) {
return this.head;
}
var previousLink = this.head,
currentLink = previousLink.next,
tempLink = null;
//Start from the element next to head to avoid changing the head.
while(currentLink !== this.head) {
//Save the next link.
tempLink = currentLink.next;
//Reverse the pointer
currentLink.next = previousLink;
//Move to next link in the list.
previousLink = currentLink;
currentLink = tempLink;
}
//Reverse the head pointer (current link is head)
currentLink.next = previousLink;
//Set the last element as head and complete the reverse operation.
this.head = previousLink;
return currentLink;
},
toString: function() {
var display = [],
currentLink = this.head;
while(currentLink) {
display.push(JSON.stringify(currentLink.data));
if(currentLink.next === this.head) {
currentLink = null;
} else {
currentLink = currentLink.next;
}
}
return display.join(' => ');
}
};
module.exports = CircularLinkedList;<file_sep>'use strict';
/** Node of the tree **/
var Node = function (data) {
this.data = data;
this.left = null;
this.right = null;
};
/** BinarySearchTree **/
var BinarySearchTree = function (rootData) {
if(rootData !== undefined || rootData !== null) {
this.root = new Node(rootData);
}
this.root = null;
};
BinarySearchTree.prototype = {
insert: function (data) {
var newNode = new Node(data);
/** Tree is empty **/
if(this.root === null) {
this.root = newNode;
return;
}
/** Tree has root node **/
var currentNode = this.root;
while(true) {
/** if data is less than node's data, traverse left **/
if(data < currentNode.data) {
/** Located end of tree. Add new Node **/
if(currentNode.left === null) {
currentNode.left = newNode;
return;
}
/** Move to next node **/
currentNode = currentNode.left;
} else { /** if data is greater than node's data, traverse right **/
/** Located end of tree. Add new Node **/
if(currentNode.right === null) {
currentNode.right = newNode;
return;
}
/** Move to next node **/
currentNode = currentNode.right;
}
}
},
search: function(data) {
var currentNode = this.root,
searchLog = 'Visiting Elements : ';
while(currentNode !== null){
if(currentNode.data === data) {
//Just logging. nothing important.
searchLog += '[ ' + currentNode.data + ' ]';
console.log(searchLog);
return currentNode;
}
//Just logging. nothing important.
searchLog += currentNode.data + ' -> ';
if(data < currentNode.data) {
currentNode = currentNode.left;
} else {
currentNode = currentNode.right;
}
}
searchLog += '[ x ]';
console.log(searchLog);
return null;
},
min: function () {
var currentNode = this.root;
/** Empty tree **/
if(currentNode === null) {
return null;
}
/** Traverse to left most to get the minimum value **/
while(currentNode.left !== null) {
currentNode = currentNode.left;
}
return currentNode;
},
max: function () {
var currentNode = this.root;
/** Empty tree **/
if(currentNode === null) {
return null;
}
/** Traverse to the right most to get the minimum value **/
while(currentNode.right !== null) {
currentNode = currentNode.right;
}
return currentNode;
}
};
module.exports = BinarySearchTree;<file_sep>'use strict';
var beautify = require('../../util/beautify'),
BinarySearchTree = require('./binarySearchTree');
function testBinarySearchTree() {
// var arr = [ 27, 14, 35, 10, 19, 31, 42 ];
// var arr = [ 1, 2, 3, 4, 5, 6 ];
var arr = [ 7, 6, 5, 14, 3, 22, 11 ];
var binarySearchTree = new BinarySearchTree();
for (var i=0; i < arr.length; i++){
binarySearchTree.insert(arr[i]);
}
console.log('BinarySearchTree', JSON.stringify(binarySearchTree, null, '\t'));
/*** Search ***/
var searchData = 32;
console.log('Search %d in tree', searchData);
var resultNode = binarySearchTree.search(searchData);
if(resultNode === null) {
console.log('Element not found');
} else {
console.log('Element found ', resultNode.data);
}
/*** Min ***/
var min = binarySearchTree.min();
if(min === null) {
console.log('Min : Empty tree');
} else {
console.log('Min value : ', min.data);
}
/*** Max ***/
var max = binarySearchTree.max();
if(max === null) {
console.log('Max : Empty tree');
} else {
console.log('Max value : ', max.data);
}
}
module.exports = function testTree() {
/** Binary Search Tree **/
beautify(testBinarySearchTree);
};<file_sep>'use strict';
var Node = function (data){
this.data = data,
this.next = null
}
var SinglyLinkedList = function () {
this._length = 0;
this.head = null;
};
SinglyLinkedList.prototype = {
add: function (value) {
var node = new Node(value),
currentNode = this.head;
//Empty node
if(!currentNode) {
this.head = node;
this._length++;
return node;
}
//non-empty node
//traverse to the end of the list.
while(currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
this._length++;
return node;
},
remove: function() {
var currentNode = this.head,
previousNode = null;
//Empty list
if(!currentNode) {
return currentNode;
}
//non-empty list with only one link
if(this._length === 1) {
this.head = null;
this._length--;
return null;
}
//non-empty list with more than one link
while(currentNode.next) {
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = null;
currentNode = null;
this._length--;
return currentNode;
},
reverse: function() {
var currentNode = this.head,
previousNode = null,
tempNode = null;
//Empty list or non-empty list with only one node.
if(this._length <= 1) {
return currentNode;
}
//non-empty list with more than one node.
while(currentNode) {
//save or not lose the next node
tempNode = currentNode.next;
//Reverse the pointer
currentNode.next = previousNode;
//Set previous node.
previousNode = currentNode;
//Retrieve or get back node chain.
currentNode = tempNode;
}
//Set the reversed list to the head
this.head = previousNode;
return previousNode;
},
find: function(value) {
var currentNode = this.head;
while(currentNode) {
if(currentNode.data === value){
return currentNode;
}
currentNode = currentNode.next;
}
return null;
},
addFirst: function(value) {
//Create new node
var newNode = new Node(value);
//Add to the first
newNode.next = this.head;
this.head = newNode;
//Increase the length
this._length++;
return newNode;
},
removeFirst: function(){
if(this.head) {
//Remove the first element
this.head = this.head.next;
//Decrement length
this._length--;
return this.head;
}
return null;
},
toString: function() {
var display = [],
currentNode = this.head;
while(currentNode) {
display.push(currentNode.data);
currentNode = currentNode.next;
}
return display.join(' => ');
}
};
module.exports = SinglyLinkedList;<file_sep>'use strict';
var swap = require('./swap');
module.exports = function selectionSort(arr) {
var sortedIndex = 0,
iterationCount = 0;
var sort = function sort() {
iterationCount++;
console.log('Iteration - #' + iterationCount);
var leastItemIndex = sortedIndex;
for(var i=sortedIndex; i < arr.length; i ++) {
leastItemIndex = arr[leastItemIndex] <= arr[i] ? leastItemIndex : i;
}
if(leastItemIndex !== sortedIndex) {
swap(arr, sortedIndex, leastItemIndex);
}
sortedIndex++;
console.log('Array after iteration %d : ', iterationCount, arr);
if(sortedIndex === arr.length-1) {
return;
}
//Iterate
sort();
}();
};<file_sep>'use strict';
var beautify = require('../../util/beautify');
var SinglyLinkedList = require('./singlyLinkedList'),
DoublyLinkedList = require('./doublyLinkedList'),
CircularLinkedList = require('./circularLinkedList');
/** Test singlyLinkedList **/
function testSinglyLinkedList() {
var singlyLinkedList = new SinglyLinkedList();
singlyLinkedList.addFirst('Muthu');
singlyLinkedList.addFirst('Kumar');
singlyLinkedList.addFirst('Bhagavath');
singlyLinkedList.addFirst('Suvetha');
console.log('SinglyLinkedList ', singlyLinkedList.toString());
// singlyLinkedList.removeFirst();
// singlyLinkedList.removeFirst();
// singlyLinkedList.removeFirst();
singlyLinkedList.remove();
// singlyLinkedList.reverse();
console.log('SinglyLinkedList ', singlyLinkedList.toString());
}
/** Test DoublyLinkedList **/
function testDoublyLinkedList() {
var doublyLinkedList = new DoublyLinkedList();
doublyLinkedList.add('1', 'Muthu');
doublyLinkedList.add('2', 'Kumar');
doublyLinkedList.add('3', 'Bhagavath');
doublyLinkedList.add('4', 'Suvetha');
console.log('length', doublyLinkedList._length);
console.log('DoublyLinkedList ', doublyLinkedList.toString());
// doublyLinkedList.remove();
// doublyLinkedList.remove();
// doublyLinkedList.remove();
doublyLinkedList.addAfter('3', {key: '5', value: 'Amal'});
console.log('length', doublyLinkedList._length);
console.log('DoublyLinkedList ', doublyLinkedList.toString());
// console.log('DoublyLinkedList ', doublyLinkedList.displayForward());
// console.log('DoublyLinkedList ', doublyLinkedList.displayBackward());
}
/** Test CircularLinkedList **/
function testCircularLinkedList() {
var circularLinkedList = new CircularLinkedList();
circularLinkedList.add('1', 'Muthu');
circularLinkedList.add('2', 'Kumar');
circularLinkedList.add('3', 'Bhagavath');
circularLinkedList.add('4', 'Suvetha');
console.log('CircularLinkedList : ', circularLinkedList.toString());
circularLinkedList.reverse();
console.log('Reversed CircularLinkedList : ', circularLinkedList.toString());
// console.log('CircularLinkedList : ', circularLinkedList.head);
// console.log('CircularLinkedList : ', circularLinkedList.head.next);
}
module.exports = function testLinkedList() {
/* SinglyLinkedList */
beautify(testSinglyLinkedList);
/* DoublyLinkedList */
beautify(testDoublyLinkedList);
/* CircularLinkedList */
beautify(testCircularLinkedList);
};<file_sep>'use strict';
/**** Doubly Linked List ****/
var DoublyLink = function(key, value){
this.data = {
key: key,
value: value
};
this.next = null;
this.previous = null;
}
var DoublyLinkedList = function(){
this.head = null;
this._length = 0;
}
DoublyLinkedList.prototype = {
add: function(key, value){
var link = new DoublyLink(key, value);
var currentLink = this.head;
//Empty list
if(!currentLink) {
this.head = link;
this._length++;
return link;
}
//non-emtpy list
//Traverse to the end of the list
while(currentLink.next) {
currentLink = currentLink.next;
}
//Add forward pointer
currentLink.next = link;
//Add backward pointer
link.previous = currentLink;
this._length++;
return link;
},
remove: function() {
var currentLink = this.head,
previousLink = null;
//Empty list
if(!currentLink) {
return currentLink;
}
//List with only one link
if(this._length === 1) {
//Emptying the List
this.head = null;
this._length--;
return this.head;
}
//Travers to the end of the list
while(currentLink.next) {
previousLink = currentLink;
currentLink = currentLink.next;
}
//Remove backward link
currentLink.previous = null;
//Remove forward link
previousLink.next = null;
//Decrement length
this._length--;
//Deallocate memory
currentLink = null;
},
addAfter: function(key, data) {
var currentLink = this.head,
keyLink =null,
nextLink = null,
newLink = new DoublyLink(data.key, data.value);
while(currentLink) {
if(currentLink.data.key === key) {
keyLink = currentLink;
nextLink = currentLink.next;
break;
}
currentLink = currentLink.next;
}
if(!keyLink) {
console.log('Link for the given key is not available in the list');
return keyLink;
}
//Point backward pointer to new link
if(nextLink){
nextLink.previous = newLink;
}
//Point forward pointer to new link
keyLink.next = newLink;
//Add forward pointer for new link.
newLink.next = nextLink;
//Add backward pointer for new link.
newLink.previous = keyLink;
//Increment length.
this._length++;
return newLink;
},
displayForward: function() {
var display = [],
currentLink = this.head;
while(currentLink) {
display.push(JSON.stringify(currentLink.data));
currentLink = currentLink.next;
}
return display.join(' => ');
},
displayBackward: function() {
var display = [],
currentLink = this.head;
//Traverse to the end
while(currentLink.next) {
currentLink = currentLink.next;
}
while(currentLink) {
display.push(JSON.stringify(currentLink.data));
currentLink = currentLink.previous;
}
return display.join(' => ');
},
toString: function() {
var display = [],
currentLink = this.head;
while(currentLink) {
display.push(JSON.stringify(currentLink.data));
currentLink = currentLink.next;
}
return display.join(' <=> ');
}
}
module.exports = DoublyLinkedList;
|
eef7965de4126a882eb2b910d500247a5b45e698
|
[
"JavaScript"
] | 7 |
JavaScript
|
MuthukumarS03/interview
|
3197099b7035c7a744cca199a1a4c825bb0d9772
|
b46498c4845a29d4d3aa4f2795584298f4767e18
|
refs/heads/master
|
<file_sep># IMAGE-SEGMENTATION-UNet
|
39faae5cd1f21da5673c8f485cf565190270e1d1
|
[
"Markdown"
] | 1 |
Markdown
|
Bhadra-statistics/IMAGE-SEGMENTATION-UNet
|
aff472399449f74ca7a480f8a84fbcb74a901b9e
|
f09ccebcedd36cb0450959e091e1f0debfccc834
|
refs/heads/master
|
<repo_name>benggrae/Spring-ES6_Study<file_sep>/springStudy/src/test/java/com/my/Controller/TodoConrollerTest.java
package com.my.Controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.event.annotation.AfterTestMethod;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
//import static org.hamcrest.Matchers.*;
@SpringBootTest
class TodoConrollerTest {
@Autowired
private WebApplicationContext webApplicationContext;
MockMvc mvc;
@BeforeEach
public void setUp() {
mvc = webAppContextSetup(webApplicationContext).build();
}
@Test
void todoListt() throws Exception{
mvc.perform(get("/todo/list"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$" , Matchers.iterableWithSize(2)))
.andExpect(jsonPath("$[0].id").value(1));
}
}
<file_sep>/springStudy/src/main/resources/data.sql
INSERT INTO T_CODE (id,attr,code_value) VALUES (1,'gender','M');
INSERT INTO T_CODE (id,attr,code_value) VALUES (2,'gender','F');
INSERT INTO User (user_Id,user_Name,gender_id,birth_Day,reg_Dt) VALUES ('D4003500','TEST',1,'20190101',NOW());
INSERT INTO T_TODO(id,todo,check_Val,end_Date,reg_Dt,reg_Id) VALUES (1,'aaa','Y','20200116',NOW(),'D4003500');
INSERT INTO T_TODO(id,todo,check_Val,end_Date,reg_Dt,reg_Id) VALUES (2,'ss','Y','20200116',NOW(),'D4003500');
<file_sep>/springStudy/src/main/resources/static/js/todo/todo.js
const ajaxHttp = (url,method,body,headers )=>{
if(headers === undefined){
headers = new Headers();
}
console.log(url);
return fetch(url,{
method ,
body ,
headers
}).then((res)=> {
console.log("then " + url);
return res.json();}
).catch(err => err)
};
const callvalue = (json) =>{
};
const innerData = (id,data) =>{
let doc = document.getElementById(id);
doc.innerHTML=data;
};
//textAreaCall
const testAdd = async () =>{
let data = await ajaxHttp("/todo/list","get");
innerData("textAreaCall",JSON.stringify(data));
}
const _init = async () =>{
let json = await ajaxHttp("/todo/list","get");
let json2 = await ajaxHttp("/todo/lists","get");
console.dir(JSON.stringify(json));
console.dir(JSON.stringify(json2));
console.log("aa")
};
<file_sep>/springStudy/src/main/java/com/my/configue/SequrityCon.java
package com.my.configue;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SequrityCon extends WebSecurityConfigurerAdapter{
@Override
public void configure(WebSecurity web) throws Exception {
/*웹도메인 리소스 Configuration*/
web.ignoring().antMatchers("/css/**", "/script/**", "image/**", "/fonts/**", "lib/**","/**");
}
}
<file_sep>/springStudy/src/main/java/com/my/Controller/TodoConroller.java
package com.my.Controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.my.domain.Todo;
import com.my.service.TodoService;
@RestController
public class TodoConroller {
@Autowired
TodoService todoService;
@GetMapping("/todo/list")
public Todo list(){
List<Todo> todos = todoService.list();
return todos.get(0);
}
@GetMapping("/todo/lists")
public Todo lists(){
List<Todo> todos = todoService.list();
return todos.get(1);
}
@GetMapping("/todo/test")
public Map<String,Object> test () {
Map<String, Object> test =new HashMap<String, Object>();
test.put("test",1);
test.put("test",2);
test.put("test",3);
test.put("test",4);
return test;
}
}
<file_sep>/springStudy/src/main/java/com/my/service/TodoService.java
package com.my.service;
import java.util.List;
import com.my.domain.Todo;
public interface TodoService {
public List<Todo> list();
}
<file_sep>/springStudy/src/main/java/com/my/domain/User.java
package com.my.domain;
import java.time.LocalDate;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.ColumnDefault;
import com.my.domain.Todo.TodoBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@ToString
@Table(name="User")
public class User {
@Id
private String userId;
private String userName;
@OneToOne
@JoinColumn(name="gender_id")
private Code gender;
@Convert(converter = LocalDateConverter.class)
private LocalDate birthDay;
@Convert(converter = LocalDateConverter.class)
private LocalDate regDt;
}
<file_sep>/springStudy/src/test/java/com/my/service/BoardServiceTest.java
package com.my.service;
import static org.assertj.core.api.Assertions.as;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.internal.matchers.Equals;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.my.domain.Board;
import com.my.domain.Code;
import com.my.domain.User;
import com.my.repository.BoardRepository;
@SpringBootTest
class BoardServiceTest {
@Autowired
BoardRepository boardRepository;
@Test
void saveAndList() {
List<Board> boardList = new ArrayList<Board>();
Code gender = new Code();
User user = User.builder().birthDay(LocalDate.now()).userId("hi").userName("hi2").gender(gender).build();
boardList.add(Board.builder().title("1st ±Ϋ").content("ΔΑΕΩΓχ1").regDt(LocalDate.now()).regId(user).build());
boardList.add(Board.builder().title("2st ±Ϋ").content("ΔΑΕΩΓχ2").regDt(LocalDate.now()).regId(user).build());
boardRepository.saveAll(boardList);
boardRepository.findAll().forEach(System.out::println);
assertEquals(boardRepository.findAll().size(), 2);
}
}
<file_sep>/springStudy/src/main/java/com/my/domain/Todo.java
package com.my.domain;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.ColumnDefault;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Entity
@Table(name="T_TODO")
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String todo;
private String checkVal;
@Convert(converter = LocalDateConverter.class)
private LocalDate endDate;
@Convert(converter = LocalDateConverter.class)
private LocalDate regDt;
@OneToOne
@JoinColumn(name="regId")
private User regId;
}
<file_sep>/springStudy/src/main/resources/templates/test/util.js
function getDom (id) {
return document.getElementById(id);
}
function appendHtml (targetID,resourceID){
let targetDom = getDom(targetID);
let addDom = document.createElement("div");
addDom.innerHTML =`<object type="text/html" data=${resourceID}>`
targetDom.appendChild(addDom);
};
export {getDom,appendHtml};
<file_sep>/springStudy/src/main/java/com/my/domain/Board.java
package com.my.domain;
import java.sql.Date;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.ColumnDefault;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@NoArgsConstructor
@ToString
@Builder
@AllArgsConstructor
@Table(name="T_BOARD")
@Entity
public class Board {
@GeneratedValue
@Id
private Long id;
private String title;
private String content;
private String category;
@OneToOne
@JoinColumn(name="regId")
private User regId;
@Convert(converter = LocalDateConverter.class)
private LocalDate regDt;
@OneToOne
@JoinColumn(name="modifyId")
private User modifyId;
@Convert(converter = LocalDateConverter.class)
private LocalDate modifyDt;
}
|
e571bb2f33858df468b32a509587cb0009aabcbd
|
[
"Java",
"SQL",
"JavaScript"
] | 11 |
Java
|
benggrae/Spring-ES6_Study
|
4aef834e289f762d6f22d72fd2dde62b3c2cca24
|
872c103dfe049b733eafd18823d98b3b2a12176d
|
refs/heads/master
|
<repo_name>rizwanhussein/CSS-Transformations-Challenge-1<file_sep>/README.md
Make this image double its size on hover by using the scale function. But don’t make it jump. Use transition to make the transformation smooth. Transition should happen within 1 second and transition-timing-function should be set to ease-in:
|
7bbed044cb2fb369ea17f03518c89f0eab27c6cb
|
[
"Markdown"
] | 1 |
Markdown
|
rizwanhussein/CSS-Transformations-Challenge-1
|
d3ae5ed6181107c3056eafb42c57f2326c90cf58
|
95d7e6236d134a5bd84e07e07b258ab6a59a9145
|
refs/heads/master
|
<repo_name>Mfigueira/slider-io<file_sep>/slider-io.js
const BREAKPOINT_SMALL = `(max-width:${425}px)`;
const BREAKPOINT_LARGE = `(min-width:${768}px)`;
const smallScreen = () => window.matchMedia(BREAKPOINT_SMALL).matches;
const largeScreen = () => window.matchMedia(BREAKPOINT_LARGE).matches;
document.querySelectorAll('.sio-container').forEach(el => {
const inner = el.querySelector('.sio-inner');
const items = el.querySelectorAll('.sio-item');
const count = items.length;
const btnNext = el.querySelector('.next button');
const btnPrev = el.querySelector('.prev button');
if (count > 3) {
const setInnerWidth = () =>
(inner.style.width = `${
(count + 1) * (smallScreen() ? 100 : largeScreen() ? 33.3333 : 50)
}%`);
window.addEventListener('resize', setInnerWidth);
setInnerWidth();
}
if (count > 1) inner.prepend(items[count - 1].cloneNode(true));
el.classList.add(`items-${count}`);
const slideStart = ml => {
inner.style.transition = 'margin 400ms';
inner.style.marginLeft =
ml ?? `-${smallScreen() ? 200 : largeScreen() ? 66.6667 : 100}%`;
};
const slideEnd = next => {
const items = el.querySelectorAll('.sio-item');
inner.style.transition = inner.style.marginLeft = '';
items[next ? 0 : items.length - 1].remove();
inner.insertAdjacentElement(
next ? 'beforeend' : 'afterbegin',
items[next ? 1 : items.length - 2].cloneNode(true)
);
};
const goNext = () => slideStart() || setTimeout(slideEnd, 400, true);
const goPrev = () => slideStart(0) || setTimeout(slideEnd, 400, false);
btnNext.addEventListener('click', goNext);
btnPrev.addEventListener('click', goPrev);
el.addEventListener('keydown', e => {
e.key === 'ArrowLeft' && goPrev();
e.key === 'ArrowRight' && goNext();
});
});
<file_sep>/README.md
# Slider IO
## What is this?
Slider IO is a versatil Items Slider Component.
## What items are supported?
An 'item' can be anything as long as the component keeps the basic HTML structure provided in order to work.
## How are the items displayed?
The component accepts from 1 to many items (unlimited), and displays on the screen up to 3 items depending on the screen size. Breakpoints are: mobile < 425px < tablet < 768px < desktop.
## Usage
To use the Slider component include the _slider-io.css_ and _slider-io.js_ files in your project. Order matters: for styles include before custom styles, and for js include after HTML has loaded (before end of body, or 'defer' in the head tag).
The HTML that you need to include in you page consist in an outer container, the 2 controls (left and right), the inner items container, and the items themselves. Like this (example with 3 items):
```html
<div class="sio-container">
<div class="sio-controls prev">
<button>←</button>
</div>
<div class="sio-inner">
<figure class="sio-item">
<img class="sio-item-img" src="..." alt="..." />
<figcaption class="sio-item-caption">...</figcaption>
</figure>
<figure class="sio-item">
<img class="sio-item-img" src="..." alt="..." />
<figcaption class="sio-item-caption">...</figcaption>
</figure>
<figure class="sio-item">
<img class="sio-item-img" src="..." alt="..." />
<figcaption class="sio-item-caption">...</figcaption>
</figure>
</div>
<div class="sio-controls next">
<button>→</button>
</div>
</div>
```
Personal style (css) can be added after the base css classes are included into the component.
**You need to at least include the "sio-container", "sio-controls prev", "sio-inner", "sio-item" (1 to many), and the "sio-controls next" for the Slider to work!**
## Can I see a working example?
Sure! In [this](https://mfigueira.github.io/slider-io/) link you can find examples with different amounts of items into the slider container. To see the flexible behavior please try different screen sizes.
|
6da63eb51971c5e4ec748c277f6925430730f6df
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Mfigueira/slider-io
|
586d15afae9ccbffcc27496de5f789347dad8941
|
cea42c9246bf879d00eb085b20b9e45b0d5452d4
|
refs/heads/main
|
<repo_name>dktran65/cmakeninja<file_sep>/runSCA.sh
#!/bin/bash
## ---Setup KW Project and Server Location
KW_PROJECT=cmake_ninja
KW_SVRNAME=localhost
KW_SVRPORT=8090
KW_INJECTFILE=kwinject.out
KW_BUILDTOOLS=/opt/klocwork/kwbuildtools20.3/bin
## --------------------------------------------------------------------------------
## --- [Cleanup Process] --- Now let do UE4 Game code and project folder clean up ...
## ---
rm -rf /S/Q kwtables
rm -rf /F/Q kwinject.out
rm -rf /F/Q build.ninja
## --------------------------------------------------------------------------------
## --- [kwinject Process] --- Monitor and trace native build, and then generate Build-Spec File
$KW_BUILDTOOLS/kwinject --output $KW_INJECTFILE sh run_native.sh
## --------------------------------------------------------------------------------
## --- [kwinject Process] --- Monitor and trace native build, and then generate Build-Spec File
$KW_BUILDTOOLS/kwbuildproject --url http://$KW_SVRNAME:$KW_SVRPORT/$KW_PROJECT -o kwtables $KW_INJECTFILE --force
## --------------------------------------------------------------------------------
## --- [kwadmin Process] --- Prep data to be Loaded on to Klocwork Portal
$KW_BUILDTOOLS/kwadmin --url http://$KW_SVRNAME:$KW_SVRPORT load $KW_PROJECT kwtables
<file_sep>/run_native.sh
#!/bin/bash
mkdir -p build.ninja && cd build.ninja && cmake .. -G Ninja && ninja
<file_sep>/run_native_inCI.sh
#!/bin/bash
mkdir -p build.ninja && cd build.ninja && cmake $1 -G Ninja && ninja
<file_sep>/main.cpp
#include <iostream>
void array_boundary_defect();
int main(int argc, char *argv[])
{
std::cout << "Hello CMake!" << std::endl;
array_boundary_defect();
return 0;
}
void array_boundary_defect()
{
char a[5] ={0,1,2,3,4};
a[5] = 5;
}
|
c9ea0d57c567c60f9943e19fdeaea049e85fa60a
|
[
"C++",
"Shell"
] | 4 |
C++
|
dktran65/cmakeninja
|
788443f208d776eeb1174ad3336194df5aa0a127
|
096b65a187eb6e6eac392d59f3d706ccf348d32b
|
refs/heads/master
|
<repo_name>pedrodz/habitsign<file_sep>/README.md
# habitsign
Habit Signature is a website to create dynamic email signatures based on your coach.me habit activity
This repo contains the scripts for http://pedrodz.com/habitsign/:
- home.html;
- get_plans.php; and,
- signature.php
<file_sep>/signature.php
<?php
# input values from URL
$nbHabitId = $_GET['habitId'];
$nbUniqueId = $_GET['id'];
$urlApiJson = "https://www.coach.me/api/v3/users/".$nbUniqueId."/activity";
//$urlApiJson = "https://www.coach.me/api/v3/users/".$nbUniqueId."/stats"; // using the stats API/JSON
//$urlApiJson = 'http://www.pedrodz.com/pedro.json'; //test purpose
$stringApi = file_get_contents($urlApiJson);
$obj = json_decode($stringApi, true);
// using the stats API/JSON:
// extract particular elements:
//$plan = $obj['plans'][$nbPlan]['name'];
//$checking = $obj['plans'][$nbPlan]['stats']['total_checkin_count'];
// text to output
//$output = 'Coach.me | ' . $plan . ' for ' . $checking . ' days'; //. " days checked in since " . $date; // Date is broken in JSON
//$habit = $obj['plans'][$nbPlan]['name'];
//$checking = $obj['plans'][$nbPlan]['stats']['total_checkin_count'];
foreach($obj['activity_items'] as $activity){
$habit = $activity['habit_id'];
if ($nbHabitId == $habit) {
$activityRichTitle = $activity['activity_rich_title'];
break;
}}
// text to output
$name = $obj['refs']['users'][0]['name'];
$nameExplode = explode(' ',trim($name));
$first_name = $nameExplode[0]; // will print Pedro
$activityRichTitle = strip_tags($activityRichTitle); // remove html tags from string
$output = ' Coach.me | '.$first_name.': ' . $activityRichTitle;
//$output = ' Coach.me | ' . $activityRichTitle;
// image processing
$h = 6*strlen($output); // change size of pic depending in nb characters
$my_img = imagecreate( $h, 20 );
$background = imagecolorallocate( $my_img, 255, 255, 255 );
$text_colour = imagecolorallocate( $my_img, 128, 128, 128 );
#$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 2, 0, 0, $output , $text_colour );
#imagesetthickness ( $my_img, 5 );
#imageline( $my_img, 30, 45, 165, 45, $line_colour );
header( "Content-type: image/png" );
imagepng( $my_img ); # Ideally to change to png, but it should be PHP http://www.thesitewizard.com/php/create-image.shtml
#imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
// delete variables (not necessary)
unset($output);
unset($activityRichTitle);
?>
<file_sep>/.htaccess
# to use PHP in HTML
# GoDaddy config: http://sagarnangare.com/parse-html-as-php-using-htaccess-file-on-godaddy/
AddHandler fcgid-script .html
FCGIWrapper /usr/local/cpanel/cgi-sys/php5 .html
# this is as to trick the browser that php is a png:
# http://stackoverflow.com/questions/25574086/random-signature-in-gmail
RewriteEngine On
RewriteRule ^signature.png signature.php [L]
<file_sep>/get_plans.php
<?php
if (isset($_POST['submit'])) {
if ($_POST['submit'] == 'Fetch habits') { // add case where user does not add url : &&
if ($_POST['userCoachmeURL']=='') {
echo "<span>Please enter your URL.</span>";
} else {
// users input their public coach.me URL
//$url = "https://www.coach.me/users/4c31cbb1193ac3e17d05/activity";
$preUrl = $_POST['userCoachmeURL'];
$url = trim($preUrl); // to trim extra spaces
// functions as to trim after "users/" and before "/":
function after ($this, $inthat)
{
if (!is_bool(strpos($inthat, $this)))
return substr($inthat, strpos($inthat,$this)+strlen($this));
};
function before ($this, $inthat)
{
return substr($inthat, 0, strpos($inthat, $this));
};
function between ($this, $that, $inthat)
{
return before ($that, after($this, $inthat));
};
$profileHash = between ('users/', '/', $url);
// extract "id" from JSON, used in the API's URL
$urlApiJsonU = "https://www.coach.me/api/v3/users/".$profileHash; // get API URL for user
$stringApiU = file_get_contents($urlApiJsonU); // get contents
$objU = json_decode($stringApiU, true); // decode JSON in user
$uniqueId = $objU['id']; // extract uniqueId (profile id) to use in activities and stats
// extract JSON from activities
$urlApiJsonA = "https://www.coach.me/api/v3/users/".$uniqueId."//activity"; // get API URL for activity
$stringApiA = file_get_contents($urlApiJsonA); // get contents
$objA = json_decode($stringApiA, true); // decode json in activity
// "activity rich title" as signature (from 'activity' API/JSON)
$allHabits = [];
$x = 0;
$y = 0;
// retrieve all habits in list of activity. Activity JSON has ~50 elements, with duplicate of habits
foreach($objA['activity_items'] as $activity){
$allHabits[$y] = $activity['habit_id'];
$y++;
}
$uniqueHabits = array_unique($allHabits); // remove duplicates
// warmth welcome:
$name = $objA['refs']['users'][0]['name'];
echo "Hi <b>" .$name. "</b>! Choose the habit would you like to show in your email signature:<br>";
// return options as list of radio buttons
foreach($objA['activity_items'] as $activity){
$habit = $activity['habit_id'];
if (in_array($habit, $uniqueHabits)) {
$habitId = $uniqueHabits[$x];
$activityRichTitle = $activity['activity_rich_title'];
$activityRichTitle = strip_tags($activityRichTitle); // strip html tags from string
echo "<input type='radio' name='habitIdRadio' value=".$habitId.">".$activityRichTitle."<br>";
$key = array_search($habit, $uniqueHabits);
unset($uniqueHabits[$key]); // remove habits from $uniqueHabits array
}
$x++;
}
echo "<input type='hidden' name='uniqueIdHidden' value=".$uniqueId.">"; // to send values to the next if
echo "<input type='submit' name='submit' value='Submit'>";
}} else if ($_POST['submit'] == 'Submit') {
# input value of plan
$nbHabitId = $_POST['habitIdRadio'];
$nbUniqueId = $_POST['uniqueIdHidden']; // example: 911327
if ($nbHabitId=='') {
echo "<br><span>Please select your habit.</span>";
} else {
// jQuery slide example: http://www.w3schools.com/jquery/jquery_slide.asp
echo "<div id='flip'><b>Gmail on a Computer:</b></div>";
echo "<div id='panel'>1) Open Gmail.<br>";
echo "2) Click the <img src='//www.google.com/help/hc/images/mail/mail_gear.png'> gear in the top right.<br>";
echo "3) Select <b>Settings</b>.<br>";
echo "4) Scroll down to the “Signature” section and click the <img src='http://signhabits.com/insert_image.png'> icon.<br>";
//echo "<img src='image_icon.png' alt='image icon' style='width:750px;height:200px'><br>";
echo "5) Click the <b>Web Address (URL)</b> tab and copy the following in the bar: <b>http://signhabits.com/signature.png?id=".$nbUniqueId."&habitId=".$nbHabitId."</b><br>";
//echo "<img src='web_address.png' alt='web address' style='width:750px;height:200px'><br>";
echo "6) Click <b>Save Changes</b> at the bottom of the page.<br></div>";
//<img url="http://pedrodz.com/habitsign/signature.png?id=716082&habitId=281185" alt="" width="400" height="20">
// delete variables (not necessary)
unset($nbHabitId);
unset($nbUniqueId);
}}
}
else{
// by default the form shows this:
echo "<p>Had problems finding people to track my habit changes<br>
So passively I made everyone that receives my emails an accountant<br>
I am not associated with Coach.me. Feel free to use <br><br>
<img src='//www.signhabits.com/example.png' style='border:1px dashed'></p>";
echo "<p>Log in to Coach.me, go to your profile, and copy-paste URL:<br>";
echo "<input type='text' name='userCoachmeURL' size='60' placeholder='https://www.coach.me/users/xxxxxxxxxxxxxxxxxxxx//activity'><br>";
echo "<input type='submit' name='submit' value='Fetch habits'></p><br>";
//echo "<span>https://www.coach.me/users/4c31cbb1193ac3e17d05//activity</span>";
}
?>
|
1cf2ecd1ff13eb3feb927e1401647a870c2f91a1
|
[
"Markdown",
"ApacheConf",
"PHP"
] | 4 |
Markdown
|
pedrodz/habitsign
|
fcd1d3226311a20acdba3ef0a16f807a2db07607
|
1abc96ef37865256b40bb2ce1af6ffd3380d618d
|
refs/heads/master
|
<repo_name>alvinli1991/leetcode-practice<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/MergeSortedArray.java
//给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
//
// 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nu
//ms2 的元素。
//
//
//
// 示例 1:
//
//
//输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
//输出:[1,2,2,3,5,6]
//
//
// 示例 2:
//
//
//输入:nums1 = [1], m = 1, nums2 = [], n = 0
//输出:[1]
//
//
//
//
// 提示:
//
//
// nums1.length == m + n
// nums2.length == n
// 0 <= m, n <= 200
// 1 <= m + n <= 200
// -109 <= nums1[i], nums2[i] <= 109
//
// Related Topics 数组 双指针
// 👍 956 👎 0
package me.alvin.leetcode.editor.cn;
import java.util.Arrays;
public class MergeSortedArray {
public static void main(String[] args) {
Solution solution = new MergeSortedArray().new Solution();
int[] test1 = new int[] {1,2,3,0,0,0};
solution.merge(test1,3,new int[]{2,5,6},3);
System.out.println(Arrays.toString(test1));
int[] test2 = new int[] {0};
solution.merge(test2,0,new int[]{1},1);
System.out.println(Arrays.toString(test2));
int[] test3 = new int[] {1};
solution.merge(test3,1,new int[]{},0);
System.out.println(Arrays.toString(test3));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int totalSize = m + n;
int index1 = m - 1;
int index2 = n - 1;
//一边反向遍历长数组,一遍确定当时那个节点的值
for (int i = totalSize - 1; i >= 0; i--) {
if (index1 >= 0 && index2 >= 0) {
if(nums1[index1] >= nums2[index2]){
nums1[i] = nums1[index1];
index1--;
}else{
nums1[i] = nums2[index2];
index2--;
}
} else if (index2 < 0) {
nums1[i] = nums1[index1];
index1--;
} else {
nums1[i] = nums2[index2];
index2--;
}
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/FlattenBinaryTreeToLinkedList.java
//给你二叉树的根结点 root ,请你将它展开为一个单链表:
//
//
// 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
// 展开后的单链表应该与二叉树 先序遍历 顺序相同。
//
//
//
//
// 示例 1:
//
//
//输入:root = [1,2,5,3,4,null,6]
//输出:[1,null,2,null,3,null,4,null,5,null,6]
//
//
// 示例 2:
//
//
//输入:root = []
//输出:[]
//
//
// 示例 3:
//
//
//输入:root = [0]
//输出:[0]
//
//
//
//
// 提示:
//
//
// 树中结点数在范围 [0, 2000] 内
// -100 <= Node.val <= 100
//
//
//
//
// 进阶:你可以使用原地算法(O(1) 额外空间)展开这棵树吗?
// Related Topics 树 深度优先搜索
// 👍 737 👎 0
package me.alvin.leetcode.editor.cn;
public class FlattenBinaryTreeToLinkedList {
public static void main(String[] args) {
Solution solution = new FlattenBinaryTreeToLinkedList().new Solution();
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
node1.left = node2;
node1.right = node5;
node2.left = node3;
node2.right = node4;
node5.right = node6;
solution.flatten(node1);
System.out.println(node1);
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if (root == null) {
return;
}
flatten(root.left);
flatten(root.right);
//将根节点的右子树放到左子树最后一个节点的右节点
TreeNode lastNode = findLastRightNode(root.left);
if (lastNode != null) {
lastNode.right = root.right;
//将根的右子树设置为左子树,根的左子树赋值为null
root.right = root.left;
root.left = null;
}
}
public TreeNode findLastRightNode(TreeNode root) {
if (root == null) {
return null;
}
TreeNode temp = root;
while (temp.right != null) {
temp = temp.right;
}
return temp;
}
}
//leetcode submit region end(Prohibit modification and deletion)
//Definition for a binary tree node.
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/BaShuZuPaiChengZuiXiaoDeShuLcof.java
//输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
//
//
//
// 示例 1:
//
// 输入: [10,2]
//输出: "102"
//
// 示例 2:
//
// 输入: [3,30,34,5,9]
//输出: "3033459"
//
//
//
// 提示:
//
//
// 0 < nums.length <= 100
//
//
// 说明:
//
//
// 输出结果可能非常大,所以你需要返回一个字符串而不是整数
// 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0
//
// Related Topics 排序
// 👍 228 👎 0
package me.alvin.leetcode.editor.cn;
import java.math.BigInteger;
public class BaShuZuPaiChengZuiXiaoDeShuLcof {
public static void main(String[] args) {
Solution solution = new BaShuZuPaiChengZuiXiaoDeShuLcof().new Solution();
System.out.println(solution.minNumber(new int[]{10,2}));
System.out.println("30".compareTo("3"));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
BigInteger min;
boolean[] visited ;
int count = 0;
String minPath;
public String minNumber(int[] nums) {
visited = new boolean[nums.length];
min = null;
minPath = "";
backtrace("",nums);
return minPath;
}
public void backtrace(String path,int[] choices){
if(count == choices.length){
if(null == min){
min = new BigInteger(path);
minPath = path;
}else{
BigInteger newNum = new BigInteger(path);
if(newNum.compareTo(min) < 0){
minPath = path;
min = newNum;
}
}
}
for(int i = 0;i<choices.length;i++){
if(visited[i]){
continue;
}
visited[i] = true;
count++;
backtrace(path+choices[i],choices);
visited[i] = false;
count--;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/PartitionEqualSubsetSum.java
//给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
//
//
//
// 示例 1:
//
//
//输入:nums = [1,5,11,5]
//输出:true
//解释:数组可以分割成 [1, 5, 5] 和 [11] 。
//
// 示例 2:
//
//
//输入:nums = [1,2,3,5]
//输出:false
//解释:数组不能分割成两个元素和相等的子集。
//
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 200
// 1 <= nums[i] <= 100
//
// Related Topics 动态规划
// 👍 758 👎 0
package me.alvin.leetcode.editor.cn;
public class PartitionEqualSubsetSum {
public static void main(String[] args) {
Solution solution = new PartitionEqualSubsetSum().new Solution();
System.out.println(solution.canPartition(new int[]{1,5,11,5}));
System.out.println(solution.canPartition(new int[]{1,2,3,5}));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
if (sum % 2 != 0) {
return false;
}
sum = sum / 2;
//对前i个物品,容量为w时,是否恰好装满
boolean[][] dp = new boolean[nums.length + 1][sum+1];
//背包容量为0,肯定装满dp[...][0]=true
for (int i = 0; i <= nums.length; i++) {
dp[i][0] = true;
}
//如果背包容量不为0,但是可选物品没有了,装不满 dp[0][...]=false
//由于i从1开始,数组索引从0开始,所以第i个物品的重量是nums[i-1]
for (int i = 1; i <= nums.length; i++) {
for (int w = 1; w <= sum; w++) {
if (nums[i - 1] > w) {
//如果第i个物品的重量大于背包,则取决于前一个物品的选择
dp[i][w] = dp[i - 1][w];
} else {
//不装入 || 装入
dp[i][w] = dp[i - 1][w] || dp[i - 1][w - nums[i - 1]];
}
}
}
return dp[nums.length][sum];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/BinaryTreeLevelOrderTraversalIi.java
//给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
//
// 例如:
//给定二叉树 [3,9,20,null,null,15,7],
//
//
// 3
// / \
// 9 20
// / \
// 15 7
//
//
// 返回其自底向上的层序遍历为:
//
//
//[
// [15,7],
// [9,20],
// [3]
//]
//
// Related Topics 树 广度优先搜索
// 👍 441 👎 0
package me.alvin.leetcode.editor.cn;
import support.TreeNode;
import java.util.*;
public class BinaryTreeLevelOrderTraversalIi{
public static void main(String[] args) {
Solution solution = new BinaryTreeLevelOrderTraversalIi().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(null == root){
return new ArrayList<>(0);
}
Stack<List<Integer>> resultStack = new Stack<>();
List<Integer> level;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
int levelSize = q.size();
level = new ArrayList<>(levelSize);
for (int i = 0; i < levelSize; i++) {
TreeNode current = q.poll();
level.add(current.val);
if(null != current.left){
q.offer(current.left);
}
if(null != current.right){
q.offer(current.right);
}
}
resultStack.push(level);
}
List<List<Integer>> result = new ArrayList<>(resultStack.size());
while(!resultStack.isEmpty()){
result.add(resultStack.pop());
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/BinaryTreeZigzagLevelOrderTraversal.java
//给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
//
// 例如:
//给定二叉树 [3,9,20,null,null,15,7],
//
//
// 3
// / \
// 9 20
// / \
// 15 7
//
//
// 返回锯齿形层序遍历如下:
//
//
//[
// [3],
// [20,9],
// [15,7]
//]
//
// Related Topics 栈 树 广度优先搜索
// 👍 449 👎 0
package me.alvin.leetcode.editor.cn;
import support.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BinaryTreeZigzagLevelOrderTraversal {
public static void main(String[] args) {
Solution solution = new BinaryTreeZigzagLevelOrderTraversal().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (null == root) {
return new ArrayList<>(0);
}
List<List<Integer>> result = new ArrayList<>();
List<Integer> level;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int flag = 1;
while (!q.isEmpty()) {
int levelSize = q.size();
level = new ArrayList<>(levelSize);
//
for (int i = 0; i < levelSize; i++) {
TreeNode current = q.poll();
if (flag % 2 == 1) {
level.add(current.val);
} else {
level.add(0, current.val);
}
if (null != current.left) {
q.offer(current.left);
}
if (null != current.right) {
q.offer(current.right);
}
}
result.add(level);
flag++;
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/test/java/me/alvin/leetcode/editor/cn/HouseRobberIiiTest.java
package me.alvin.leetcode.editor.cn;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
/**
* @author <NAME>
* @since 2021/4/2 18:36
*/
public class HouseRobberIiiTest {
@Test
public void test1(){
HouseRobberIii.Solution solution = new HouseRobberIii().new Solution();
HouseRobberIii.TreeNode node3_t = new HouseRobberIii.TreeNode(3);
HouseRobberIii.TreeNode node2_l = new HouseRobberIii.TreeNode(2);
HouseRobberIii.TreeNode node3_r = new HouseRobberIii.TreeNode(3);
HouseRobberIii.TreeNode node3_lr = new HouseRobberIii.TreeNode(3);
HouseRobberIii.TreeNode node1_r = new HouseRobberIii.TreeNode(1);
node3_t.left = node2_l;
node3_t.right = node3_r;
node2_l.right = node3_lr;
node3_r.right = node1_r;
System.out.println(solution.rob(node3_t));
assertThat(solution.rob(node3_t),equalTo(7));
}
@Test
public void test2(){
HouseRobberIii.Solution solution = new HouseRobberIii().new Solution();
HouseRobberIii.TreeNode node3_t = new HouseRobberIii.TreeNode(3);
HouseRobberIii.TreeNode node4_l = new HouseRobberIii.TreeNode(4);
HouseRobberIii.TreeNode node5_r = new HouseRobberIii.TreeNode(5);
HouseRobberIii.TreeNode node1_l = new HouseRobberIii.TreeNode(1);
HouseRobberIii.TreeNode node3_lr = new HouseRobberIii.TreeNode(3);
HouseRobberIii.TreeNode node1_r = new HouseRobberIii.TreeNode(1);
node3_t.left = node4_l;
node3_t.right = node5_r;
node4_l.left = node1_l;
node4_l.right = node3_lr;
node5_r.right = node1_r;
System.out.println(solution.rob(node3_t));
assertThat(solution.rob(node3_t),equalTo(9));
}
@Test
public void test3(){
HouseRobberIii.Solution solution = new HouseRobberIii().new Solution();
HouseRobberIii.TreeNode node1 = new HouseRobberIii.TreeNode(1);
HouseRobberIii.TreeNode node2 = new HouseRobberIii.TreeNode(2);
HouseRobberIii.TreeNode node3 = new HouseRobberIii.TreeNode(3);
node1.left = node2;
node1.right = node3;
System.out.println(solution.rob(node1));
}
@Test
public void test4(){
HouseRobberIii.Solution solution = new HouseRobberIii().new Solution();
HouseRobberIii.TreeNode node4 = new HouseRobberIii.TreeNode(4);
HouseRobberIii.TreeNode node1 = new HouseRobberIii.TreeNode(1);
HouseRobberIii.TreeNode node2 = new HouseRobberIii.TreeNode(2);
HouseRobberIii.TreeNode node3 = new HouseRobberIii.TreeNode(3);
node4.left = node1;
node1.left = node2;
node2.left = node3;
System.out.println(solution.rob(node4));
}
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/RangeSumQueryImmutable.java
//给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。
//
//
//
// 实现 NumArray 类:
//
//
// NumArray(int[] nums) 使用数组 nums 初始化对象
// int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点(也就是 s
//um(nums[i], nums[i + 1], ... , nums[j]))
//
//
//
//
// 示例:
//
//
//输入:
//["NumArray", "sumRange", "sumRange", "sumRange"]
//[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
//输出:
//[null, 1, -1, -3]
//
//解释:
//NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
//numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
//numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
//numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
//
//
//
//
// 提示:
//
//
// 0 <= nums.length <= 104
// -105 <= nums[i] <= 105
// 0 <= i <= j < nums.length
// 最多调用 104 次 sumRange 方法
//
//
//
// Related Topics 动态规划
// 👍 328 👎 0
package me.alvin.leetcode.editor.cn;
public class RangeSumQueryImmutable {
public static void main(String[] args) {
NumArray2 solution = new RangeSumQueryImmutable().new NumArray2(new int[]{-2, 0, 3, -5, 2, -1});
System.out.println(solution.sumRange(0, 2));
System.out.println(solution.sumRange(2, 5));
System.out.println(solution.sumRange(0, 5));
}
//leetcode submit region begin(Prohibit modification and deletion)
class NumArray {
//前缀和
int[] preSum;
int[] nums;
public NumArray(int[] nums) {
this.nums = nums;
preSum = new int[nums.length];
preSum[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
preSum[i] = preSum[i - 1] + nums[i];
}
}
public int sumRange(int left, int right) {
return preSum[right] - preSum[left] + nums[left];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
//leetcode submit region end(Prohibit modification and deletion)
class NumArray2 {
//前缀和
int[] preSum;
public NumArray2(int[] nums) {
//前缀和数组多一个占位元素0,统一操作以及消除index=0的特殊情况
preSum = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
preSum[i + 1] = preSum[i] + nums[i];
}
}
public int sumRange(int left, int right) {
return preSum[right + 1] - preSum[left];
}
}
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/SumRootToLeafNumbers.java
//给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。
//
//
// 每条从根节点到叶节点的路径都代表一个数字:
//
//
// 例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
//
//
// 计算从根节点到叶节点生成的 所有数字之和 。
//
// 叶节点 是指没有子节点的节点。
//
//
//
// 示例 1:
//
//
//输入:root = [1,2,3]
//输出:25
//解释:
//从根到叶子节点路径 1->2 代表数字 12
//从根到叶子节点路径 1->3 代表数字 13
//因此,数字总和 = 12 + 13 = 25
//
// 示例 2:
//
//
//输入:root = [4,9,0,5,1]
//输出:1026
//解释:
//从根到叶子节点路径 4->9->5 代表数字 495
//从根到叶子节点路径 4->9->1 代表数字 491
//从根到叶子节点路径 4->0 代表数字 40
//因此,数字总和 = 495 + 491 + 40 = 1026
//
//
//
//
// 提示:
//
//
// 树中节点的数目在范围 [1, 1000] 内
// 0 <= Node.val <= 9
// 树的深度不超过 10
//
//
//
// Related Topics 树 深度优先搜索
// 👍 357 👎 0
package me.alvin.leetcode.editor.cn;
import support.TreeNode;
import support.TreeTools;
import java.util.LinkedList;
import java.util.List;
public class SumRootToLeafNumbers {
public static void main(String[] args) {
Solution solution = new SumRootToLeafNumbers().new Solution();
TreeNode root = null;
root = TreeTools.buildTree(new Integer[]{1, 2, 3}, root, 0);
System.out.println(solution.sumNumbers(root));
System.out.println(solution.travel(root,0));
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
List<Integer> nums = new LinkedList<>();
StringBuilder path = new StringBuilder();
travel(root, path, nums);
return nums.stream().mapToInt(Integer::intValue)
.sum();
}
private void travel(TreeNode root, StringBuilder path, List<Integer> nums) {
if (null == root) {
return;
}
path.append(root.val);
if (null == root.left && null == root.right) {
nums.add(Integer.parseInt(path.toString()));
}
travel(root.left, new StringBuilder(path), nums);
travel(root.right, new StringBuilder(path), nums);
}
/**
*
*
* @param root
* @param preSum
* @return
*/
public int travel(TreeNode root, int preSum) {
if (root == null) {
return 0;
}
int sum = preSum * 10 + root.val;
if (null == root.left && null == root.right) {
return sum;
}
return travel(root.left, sum) + travel(root.right, sum);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/BaShuZiFanYiChengZiFuChuanLcof.java
//给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可
//能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
//
//
//
// 示例 1:
//
// 输入: 12258
//输出: 5
//解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi"
//
//
//
// 提示:
//
//
// 0 <= num < 231
//
// 👍 236 👎 0
package me.alvin.leetcode.editor.cn;
public class BaShuZiFanYiChengZiFuChuanLcof{
public static void main(String[] args) {
Solution solution = new BaShuZiFanYiChengZiFuChuanLcof().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int translateNum(int num) {
String s = String.valueOf(num);
int[] dp = new int[s.length()+1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= s.length(); i++) {
String temp = s.substring(i-2,i);
if(temp.compareTo("10") >=0 && temp.compareTo("25")<=0){
dp[i] = dp[i-1]+dp[i-2];
}else{
dp[i] = dp[i-1];
}
}
return dp[s.length()];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/support/TreeTools.java
package support;
/**
* @author <NAME>
* @since 2021/5/10 11:10
*/
public class TreeTools {
public static TreeNode buildTree(Integer[] nodes) {
TreeNode root = null;
root = buildTree(nodes, root, 0);
return root;
}
public static TreeNode buildTree(Integer[] nodes, int i) {
TreeNode root = null;
root = buildTree(nodes, root, 0);
return root;
}
public static TreeNode buildTree(Integer[] nodes, TreeNode root, int i) {
if (i < nodes.length) {
if (nodes[i] != null) {
root = new TreeNode(nodes[i]);
root.left = buildTree(nodes, root.left, 2 * i + 1);
root.right = buildTree(nodes, root.right, 2 * (i + 1));
}
}
return root;
}
}
<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/MergeTwoSortedLists.java
//将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
//
//
//
// 示例 1:
//
//
//输入:l1 = [1,2,4], l2 = [1,3,4]
//输出:[1,1,2,3,4,4]
//
//
// 示例 2:
//
//
//输入:l1 = [], l2 = []
//输出:[]
//
//
// 示例 3:
//
//
//输入:l1 = [], l2 = [0]
//输出:[0]
//
//
//
//
// 提示:
//
//
// 两个链表的节点数目范围是 [0, 50]
// -100 <= Node.val <= 100
// l1 和 l2 均按 非递减顺序 排列
//
// Related Topics 递归 链表
// 👍 1709 👎 0
package me.alvin.leetcode.editor.cn;
import support.ListNode;
import support.ListTools;
public class MergeTwoSortedLists {
public static void main(String[] args) {
Solution solution = new MergeTwoSortedLists().new Solution();
ListNode l1 = ListTools.buildLinkedList(new int[]{1,2,3});
ListNode l2 = ListTools.buildLinkedList(new int[]{1,3,4});
ListNode merge = solution.mergeTwoLists2(l1, l2);
System.out.println(merge);
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode(-1);
ListNode tail = dummyNode;
ListNode node1 = l1;
ListNode node2 = l2;
while (node1 != null && node2 != null) {
if (node1.val < node2.val) {
tail.next = node1;
node1 = node1.next;
tail = tail.next;
} else if (node1.val > node2.val) {
tail.next = node2;
node2 = node2.next;
tail = tail.next;
} else {
tail.next = node1;
node1 = node1.next;
tail.next.next = node2;
node2 = node2.next;
tail = tail.next.next;
}
}
if (node1 == null) {
tail.next = node2;
}
if (node2 == null) {
tail.next = node1;
}
return dummyNode.next;
}
/**
* 与上面一个不同点在于,把相等的情况归到某一个中,这样tail指针的移动可以统一
* @param l1
* @param l2
* @return
*/
public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode(-1);
ListNode tail = dummyNode;
ListNode node1 = l1;
ListNode node2 = l2;
while (node1 != null && node2 != null) {
if (node1.val < node2.val) {
tail.next = node1;
node1 = node1.next;
} else {
tail.next = node2;
node2 = node2.next;
}
tail = tail.next;
}
if (node1 == null) {
tail.next = node2;
}
if (node2 == null) {
tail.next = node1;
}
return dummyNode.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/ReverseNodesInKGroup.java
//给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
//
// k 是一个正整数,它的值小于或等于链表的长度。
//
// 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
//
// 进阶:
//
//
// 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
// 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
//
//
//
//
// 示例 1:
//
//
//输入:head = [1,2,3,4,5], k = 2
//输出:[2,1,4,3,5]
//
//
// 示例 2:
//
//
//输入:head = [1,2,3,4,5], k = 3
//输出:[3,2,1,4,5]
//
//
// 示例 3:
//
//
//输入:head = [1,2,3,4,5], k = 1
//输出:[1,2,3,4,5]
//
//
// 示例 4:
//
//
//输入:head = [1], k = 1
//输出:[1]
//
//
//
//
//
// 提示:
//
//
// 列表中节点的数量在范围 sz 内
// 1 <= sz <= 5000
// 0 <= Node.val <= 1000
// 1 <= k <= sz
//
// Related Topics 链表
// 👍 1102 👎 0
package me.alvin.leetcode.editor.cn;
import support.ListNode;
import support.ListTools;
public class ReverseNodesInKGroup {
public static void main(String[] args) {
Solution solution = new ReverseNodesInKGroup().new Solution();
ListNode l1 = ListTools.buildLinkedList(new int[]{1,2,3,4,5,6,7,8});
System.out.println(solution.reverseKGroup(l1,3));
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (k == 1) {
return head;
}
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
//找到可以操作的第一个k区间
ListNode guard = dummyHead;
ListNode nextGuard = guard.next;
ListNode walk = guard;
boolean flag = true;
while (true) {
//走k步,如果到了null,则不继续
for (int i = 0; i < k; i++) {
walk = walk.next;
if (walk == null) {
flag = false;
break;
}
}
if(!flag){
break;
}
//翻转某个区间的节点并接上
guard.next = reverseBetweenByHeadInsert(guard.next, 1, k);
//设置下一个区间的参数
guard = nextGuard;
nextGuard = guard.next;
walk = guard;
}
return dummyHead.next;
}
/**
* 前插法
*
* @param head
* @param left
* @param right
* @return
*/
public ListNode reverseBetweenByHeadInsert(ListNode head, int left, int right) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
//找到需要翻转的前一个节点,以及需要翻转区间的第一个节点
ListNode guard = dummyHead;
ListNode last = dummyHead.next;
for (int i = 0; i < left - 1; i++) {
guard = guard.next;
last = last.next;
}
//例如是操作区间是[2,4],那么需要操作节点是node3,node4,及两次
for (int i = 0; i < right - left; i++) {
ListNode remove = last.next;
last.next = remove.next;
remove.next = guard.next;
guard.next = remove;
}
return dummyHead.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/ShuDeZiJieGouLcof.java
//输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
//
// B是A的子结构, 即 A中有出现和B相同的结构和节点值。
//
// 例如:
//给定的树 A:
//
// 3
// / \
// 4 5
// / \
// 1 2
//给定的树 B:
//
// 4
// /
// 1
//返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
//
// 示例 1:
//
// 输入:A = [1,2,3], B = [3,1]
//输出:false
//
//
// 示例 2:
//
// 输入:A = [3,4,5,1,2], B = [4,1]
//输出:true
//
// 限制:
//
// 0 <= 节点个数 <= 10000
// Related Topics 树
// 👍 287 👎 0
package me.alvin.leetcode.editor.cn;
import support.TreeNode;
import support.TreeTools;
public class ShuDeZiJieGouLcof {
public static void main(String[] args) {
Solution solution = new ShuDeZiJieGouLcof().new Solution();
TreeNode A = TreeTools.buildTree(new Integer[]{4, 2, 3, 4, 5, 6, 7, 8, 9});
TreeNode B = TreeTools.buildTree(new Integer[]{4, 8, 9});
System.out.println(solution.isSubStructure(A, B));
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
//前序遍历每个节点,然后判断是否一致
if (null == A || null == B) {
return false;
}
return dfs(A, B)|| isSubStructure(A.left, B) || isSubStructure(A.right, B);
}
public boolean dfs(TreeNode A, TreeNode B) {
if (null == B) return true;
if (A == null || A.val != B.val) return false;
return dfs(A.left, B.left) && dfs(A.right, B.right);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/KthLargestElementInAnArray.java
//在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
//
// 示例 1:
//
// 输入: [3,2,1,5,6,4] 和 k = 2
//输出: 5
//
//
// 示例 2:
//
// 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
//输出: 4
//
// 说明:
//
// 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
// Related Topics 堆 分治算法
// 👍 1105 👎 0
package me.alvin.leetcode.editor.cn;
import java.util.PriorityQueue;
public class KthLargestElementInAnArray {
public static void main(String[] args) {
Solution solution = new KthLargestElementInAnArray().new Solution();
// System.out.println(solution.findKthLargest(new int[]{3, 2, 1, 5, 6, 4}, 2));
// System.out.println(solution.findKthLargest(new int[]{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4));
System.out.println(solution.findKthLargest(new int[]{2, 8, 3, 1, 6, 5, 9}, 3));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findKthLargest(int[] nums, int k) {
//使用小顶堆
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int val : nums) {
if (pq.size() < k) {
pq.offer(val);
} else if (pq.peek() < val) {
pq.poll();
pq.offer(val);
}
}
return pq.peek();
}
public int findKthLargest2(int[] nums, int k) {
//使用小顶堆
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int val : nums) {
pq.offer(val);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/JiQiRenDeYunDongFanWeiLcof.java
//地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一
//格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但
//它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
//
//
//
// 示例 1:
//
// 输入:m = 2, n = 3, k = 1
//输出:3
//
//
// 示例 2:
//
// 输入:m = 3, n = 1, k = 0
//输出:1
//
//
// 提示:
//
//
// 1 <= n,m <= 100
// 0 <= k <= 20
//
// 👍 298 👎 0
package me.alvin.leetcode.editor.cn;
public class JiQiRenDeYunDongFanWeiLcof {
public static void main(String[] args) {
Solution solution = new JiQiRenDeYunDongFanWeiLcof().new Solution();
System.out.println(solution.movingCount(2,3,1));
System.out.println(solution.movingCount(3,1,0));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
boolean visited[][];
int count ;
public int movingCount(int m, int n, int k) {
count = 0;
visited = new boolean[m][n];
dfs(m, n, 0, 0, k);
return count;
}
public void dfs(int rows, int cols, int row, int col, int k) {
//越界的不要
if (row < 0 || row >= rows || col < 0 || col >= cols) {
return;
}
//被使用过的不要
if (visited[row][col]) {
return;
}
//不符合和的不要
if (sum(row) + sum(col) > k) {
return;
}
visited[row][col] = true;
count++;
/**
* 由于从(0,0)开始,所以只可能是向下或者向右走
*/
//向下走
dfs(rows, cols, row + 1, col, k);
//向右走
dfs(rows, cols, row, col + 1, k);
}
public int sum(int row) {
int amount = 0;
while(row !=0){
amount += row % 10;
row = row / 10;
}
return amount;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/MaxSumOfRectangleNoLargerThanK.java
//给你一个 m x n 的矩阵 matrix 和一个整数 k ,找出并返回矩阵内部矩形区域的不超过 k 的最大数值和。
//
// 题目数据保证总会存在一个数值和不超过 k 的矩形区域。
//
//
//
// 示例 1:
//
//
//输入:matrix = [[1,0,1],[0,-2,3]], k = 2
//输出:2
//解释:蓝色边框圈出来的矩形区域 [[0, 1], [-2, 3]] 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。
//
//
// 示例 2:
//
//
//输入:matrix = [[2,2,-1]], k = 3
//输出:3
//
//
//
//
// 提示:
//
//
// m == matrix.length
// n == matrix[i].length
// 1 <= m, n <= 100
// -100 <= matrix[i][j] <= 100
// -105 <= k <= 105
//
//
//
//
// 进阶:如果行数远大于列数,该如何设计解决方案?
// Related Topics 队列 二分查找 动态规划
// 👍 293 👎 0
package me.alvin.leetcode.editor.cn;
public class MaxSumOfRectangleNoLargerThanK {
public static void main(String[] args) {
Solution solution = new MaxSumOfRectangleNoLargerThanK().new Solution();
// System.out.println(solution.maxSumSubmatrix(new int[][]{{1,0,1},{0,-2,3}},2));
// System.out.println(solution.maxSumSubmatrix(new int[][]{{2,2,-1}},3));
System.out.println(solution.maxSumSubmatrix(new int[][]{{2,2,-1}},0));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int maxSumSubmatrix(int[][] matrix, int k) {
PreSumMatrix preSumMatrix = new PreSumMatrix(matrix);
int rowCount = matrix.length;
int colCount = matrix[0].length;
int max = Integer.MIN_VALUE;
for (int row1 = 0; row1 < rowCount; row1++) {
for (int col1 = 0; col1 < colCount; col1++) {
for (int row2 = row1; row2 < rowCount; row2++) {
for (int col2 = row2; col2 < colCount; col2++) {
int matrixSum = preSumMatrix.sumRegion(row1, col1, row2, col2);
if (matrixSum <= k && matrixSum > max) {
max = Math.max(max, matrixSum);
}
}
}
}
}
return max;
}
}
class PreSumMatrix {
/**
* 二维前缀和:以(0,0) 、(row,col)为左上、右下顶点的矩形
*/
int[][] preSum2Dim;
public PreSumMatrix(int[][] matrix) {
int rowCount = matrix.length;
if (rowCount > 0) {
int colCount = matrix[0].length;
preSum2Dim = new int[rowCount + 1][colCount + 1];
for (int row = 0; row < rowCount; row++) {
for (int col = 0; col < colCount; col++) {
preSum2Dim[row + 1][col + 1] = preSum2Dim[row][col + 1] + preSum2Dim[row + 1][col]
- preSum2Dim[row][col] + matrix[row][col];
}
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return preSum2Dim[row2 + 1][col2 + 1] - preSum2Dim[row1][col2 + 1] - preSum2Dim[row2 + 1][col1] + preSum2Dim[row1][col1];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/MaximumDepthOfBinaryTree.java
//给定一个二叉树,找出其最大深度。
//
// 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
//
// 说明: 叶子节点是指没有子节点的节点。
//
// 示例:
//给定二叉树 [3,9,20,null,null,15,7],
//
// 3
// / \
// 9 20
// / \
// 15 7
//
// 返回它的最大深度 3 。
// Related Topics 树 深度优先搜索 递归
// 👍 883 👎 0
package me.alvin.leetcode.editor.cn;
import support.TreeNode;
public class MaximumDepthOfBinaryTree {
public static void main(String[] args) {
Solution solution = new MaximumDepthOfBinaryTree().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max;
public int maxDepth(TreeNode root) {
max = 0;
dfs(root);
return max;
}
/**
* 根节点到最远叶子节点的最长路径上的节点数
*
* @param root
* @return
*/
public int dfs(TreeNode root) {
if (null == root) {
return 0;
}
int left = dfs(root.left);
int right = dfs(root.right);
//因为以root为节点的最大深度不包含节点本身,所以+1
int depth = Math.max(left, right) + 1;
max = Math.max(max, depth);
return depth;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/ShuZuZhongDeNiXuDuiLcof.java
//在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
//
//
//
// 示例 1:
//
// 输入: [7,5,6,4]
//输出: 5
//
//
//
// 限制:
//
// 0 <= 数组长度 <= 50000
// 👍 442 👎 0
package me.alvin.leetcode.editor.cn;
public class ShuZuZhongDeNiXuDuiLcof {
public static void main(String[] args) {
Solution solution = new ShuZuZhongDeNiXuDuiLcof().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
int[] temp;
int[] holder;
public int reversePairs(int[] nums) {
this.holder = nums;
temp = new int[nums.length];
return mergeSort(0, nums.length - 1);
}
/**
* 对区间 [left,right] 进行排序
*
* @param left
* @param right
* @return
*/
public int mergeSort(int left, int right) {
//子数组长度为1
if (left >= right) {
return 0;
}
//划分
int mid = left + (right - left) / 2;
int result = mergeSort(left, mid) + mergeSort(mid + 1, right);
//合并
int i = left;
int j = mid + 1;
//将holder[lo..hi]复制到temp[lo..hi]
for (int k = left; k <= right; k++) {
temp[k] = holder[k];
}
//归并到holder中
for (int k = left; k <= right; k++) {
if (i > mid) {//左半边用尽(取右半边元素)
holder[k] = temp[j++];
} else if (j > right) { //右半边用尽(取左半边元素)
holder[k] = temp[i++];
} else if (temp[i] <= temp[j]) {//左边元素小于等于右边元素,取左边元素
holder[k] = temp[i++];
}else{ //左边元素大于等于右边元素,取右边元素;计算逆序对个数
holder[k] = temp[j++];
result += mid-i+1;//逆序对,左边比右边多的数字
}
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/support/QuickSort.java
package support;
/**
* @author <NAME>
* @since 2021/5/31 12:00
*/
public class QuickSort {
public static void sort(Comparable[] a) {
sort(a, 0, a.length - 1);
}
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) {
return;
}
int j = partition(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}
private static int partition(Comparable[] a, int lo, int hi) {
//将数组切分为a[lo..i-1], a[i], a[i+1..hi]
int i = lo;
int j = hi + 1;//左右扫描指针
Comparable v = a[lo];
//扫描左右,检查扫描是否简述并交换元素
while (true) {
//从左往右扫描,知道找到一个比v大的或者到最后一个
while (SortTemplate.less(a[++i], v)) {
if (i == hi) {
break;
}
}
//从右往左扫描,直到找到一个比v小的或者到第一个
while (SortTemplate.less(v, a[--j])) {
if (j == lo) {
break;
}
}
//如果左右指针相遇时,退出循环
if (i >= j) {
break;
}
//如果他们没有相遇,则交换他们,保证左边的比v小,右边的比v大
SortTemplate.swap(a, i, j);
}
//将v = a[j]放入正确的位置
SortTemplate.swap(a, lo, j);
//达成a[lo..j-1] <= a[j] <= a[j+1..hi]
return j;
}
}
<file_sep>/src/main/java/support/InsertSort.java
package support;
/**
* @author <NAME>
* @since 2021/5/31 11:04
*/
public class InsertSort {
public static void sort(Comparable[] a) {
int length = a.length;
for (int i = 1; i < length; i++) {
//将a[i] 插入到a[i-1],a[i-2]……中去
for (int j = i; j > 0 && SortTemplate.less(a[j], a[j - 1]); j--) {
SortTemplate.swap(a, j, j - 1);
}
}
}
}
<file_sep>/src/main/java/support/ListTools.java
package support;
/**
* @author <NAME>
* @since 2021/5/18 21:54
*/
public class ListTools {
public static ListNode buildLinkedList(int[] nums) {
if(nums.length == 0){
return null;
}
ListNode first = new ListNode(nums[0]);
ListNode last = first;
for (int i = 1; i < nums.length; i++) {
ListNode newNode = new ListNode(nums[i]);
last.next = newNode;
last = newNode;
}
return first;
}
public static ListNode buildLinkedList(int[] nums, ListNode node, int i) {
if (i < nums.length) {
node = new ListNode(nums[i]);
node.next = buildLinkedList(nums, node.next, i + 1);
}
return node;
}
}
<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/ShuZuZhongZhongFuDeShuZiLcof.java
//找出数组中重复的数字。
//
//
//在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请
//找出数组中任意一个重复的数字。
//
// 示例 1:
//
// 输入:
//[2, 3, 1, 0, 2, 5, 3]
//输出:2 或 3
//
//
//
//
// 限制:
//
// 2 <= n <= 100000
// Related Topics 数组 哈希表
// 👍 451 👎 0
package me.alvin.leetcode.editor.cn;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ShuZuZhongZhongFuDeShuZiLcof {
public static void main(String[] args) {
Solution solution = new ShuZuZhongZhongFuDeShuZiLcof().new Solution();
System.out.println(solution.findRepeatNumber(new int[]{2, 3, 1, 0, 2, 5, 3}));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findRepeatNumber(int[] nums) {
return exchange(nums);
}
public int hashMap(int[] nums) {
Map<Integer, Integer> numCount = new HashMap();
for (int i = 0; i < nums.length; i++) {
int holder = nums[i];
numCount.put(holder, numCount.getOrDefault(holder, 0) + 1);
if (numCount.get(holder) > 1) {
return holder;
}
}
return -1;
}
public int hashSet(int[] nums) {
Set<Integer> numCount = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
int holder = nums[i];
if (numCount.contains(holder)) {
return holder;
}
numCount.add(holder);
}
return -1;
}
/**
* 通过下标交换
* @param nums
* @return
*/
public int exchange(int[] nums) {
int i = 0;
while (i < nums.length) {
int num = nums[i];
if (num == i) {
i++;
continue;
}
if (num == nums[num]) {
return num;
}
int tmp = nums[num];
nums[num] = num;
nums[i] = tmp;
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/SameTree.java
//给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。
//
// 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
//
//
//
// 示例 1:
//
//
//输入:p = [1,2,3], q = [1,2,3]
//输出:true
//
//
// 示例 2:
//
//
//输入:p = [1,2], q = [1,null,2]
//输出:false
//
//
// 示例 3:
//
//
//输入:p = [1,2,1], q = [1,1,2]
//输出:false
//
//
//
//
// 提示:
//
//
// 两棵树上的节点数目都在范围 [0, 100] 内
// -104 <= Node.val <= 104
//
// Related Topics 树 深度优先搜索
// 👍 584 👎 0
package me.alvin.leetcode.editor.cn;
public class SameTree {
public static void main(String[] args) {
Solution solution = new SameTree().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return travel(p).equals(travel(q));
}
/**
* 使用前序遍历,序列化树然后再进行比较。
* 此种做法需要额外的空间存储序列化结果,空间复杂度较高
*
* @param root
* @return
*/
public String travel(TreeNode root) {
if (null == root) {
return "null";
}
StringBuilder sb = new StringBuilder();
sb.append(root.val);
String left = travel(root.left);
String right = travel(root.right);
sb.append(left);
sb.append(right);
return sb.toString();
}
/**
* 和上面的解法来看也是递归,但是它不需要额外的空间,是就地比较
*
* @param p
* @param q
* @return
*/
public boolean deepTravel(TreeNode p, TreeNode q) {
if (null == p && null == q) {
return true;
} else if (null == p) {
return false;
} else if (null == q) {
return false;
} else if (p.val != q.val) {
return false;
} else {
return deepTravel(p.left, q.left) && deepTravel(p.right, q.right);
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}<file_sep>/src/main/java/me/alvin/leetcode/editor/cn/OnesAndZeroes.java
//给你一个二进制字符串数组 strs 和两个整数 m 和 n 。
//
//
// 请你找出并返回 strs 的最大子集的大小,该子集中 最多 有 m 个 0 和 n 个 1 。
//
// 如果 x 的所有元素也是 y 的元素,集合 x 是集合 y 的 子集 。
//
//
//
//
// 示例 1:
//
//
//输入:strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3
//输出:4
//解释:最多有 5 个 0 和 3 个 1 的最大子集是 {"10","0001","1","0"} ,因此答案是 4 。
//其他满足题意但较小的子集包括 {"0001","1"} 和 {"10","1","0"} 。{"111001"} 不满足题意,因为它含 4 个 1 ,大于
//n 的值 3 。
//
//
// 示例 2:
//
//
//输入:strs = ["10", "0", "1"], m = 1, n = 1
//输出:2
//解释:最大的子集是 {"0", "1"} ,所以答案是 2 。
//
//
//
//
// 提示:
//
//
// 1 <= strs.length <= 600
// 1 <= strs[i].length <= 100
// strs[i] 仅由 '0' 和 '1' 组成
// 1 <= m, n <= 100
//
// Related Topics 动态规划
// 👍 382 👎 0
package me.alvin.leetcode.editor.cn;
public class OnesAndZeroes {
public static void main(String[] args) {
Solution solution = new OnesAndZeroes().new Solution();
System.out.println(solution.findMaxForm(new String[]{"10", "0001", "111001", "1", "0"}, 5, 3));
System.out.println(solution.findMaxForm(new String[]{"10", "0", "1"}, 1, 1));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
//前N个中,当0为m,1为n时,最多的子集个数
int[][][] dp = new int[strs.length + 1][m + 1][n + 1];
ItemCount[] itemCounts = trans(strs);
for (int zeroCnt = 0; zeroCnt <= m; zeroCnt++) {
for (int oneCnt = 0; oneCnt <= n; oneCnt++) {
//在有i个0,j个1时,对前k个字符串进行选择
for (int k = 1; k <= itemCounts.length; k++) {
ItemCount theItem = itemCounts[k - 1];
if (theItem.getZeroCount() > zeroCnt || theItem.getOneCount() > oneCnt) {
//无法选当前元素,则大小取决与前k-1
dp[k][zeroCnt][oneCnt] = dp[k - 1][zeroCnt][oneCnt];
} else {
dp[k][zeroCnt][oneCnt] = Math.max(
dp[k - 1][zeroCnt][oneCnt], //不选此元素
dp[k - 1][zeroCnt - theItem.getZeroCount()][oneCnt - theItem.getOneCount()] + 1 //选此元素
);
}
}
}
}
return dp[strs.length][m][n];
}
public ItemCount[] trans(String[] strs) {
ItemCount[] result = new ItemCount[strs.length];
for (int i = 0; i < strs.length; i++) {
String item = strs[i];
ItemCount count = new ItemCount();
for (int j = 0; j < item.length(); j++) {
if ('0' == item.charAt(j)) {
count.addZero();
} else {
count.addOne();
}
}
result[i] = count;
}
return result;
}
public int findMaxForm2Dim(String[] strs, int m, int n) {
int[][] dp = new int[m + 1][n + 1];
for (String s : strs) {
int[] count = countZeroesOnes(s);
for (int zeroes = m; zeroes >= count[0]; zeroes--) {
for (int ones = n; ones >= count[1]; ones--) {
dp[zeroes][ones] = Math.max(1 + dp[zeroes - count[0]][ones - count[1]], dp[zeroes][ones]);
}
}
}
return dp[m][n];
}
public int[] countZeroesOnes(String s) {
int[] c = new int[2];
for (int i = 0; i < s.length(); i++) {
c[s.charAt(i) - '0']++;
}
return c;
}
}
class ItemCount {
int zeroCount;
int oneCount;
public ItemCount() {
this.zeroCount = 0;
this.oneCount = 0;
}
public void addZero() {
this.zeroCount++;
}
public void addOne() {
this.oneCount++;
}
public int getZeroCount() {
return zeroCount;
}
public int getOneCount() {
return oneCount;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
|
76e2499921be093755050b042c3f536e37148611
|
[
"Java"
] | 25 |
Java
|
alvinli1991/leetcode-practice
|
48b5842d53e0d6547a6b3fb16d4bb0cf7f21d246
|
4aeb39fd335f87ef70a35ef8643af46a75fc3681
|
refs/heads/master
|
<file_sep>p = link_to "New", new_todo_path
- @todos.each do |todo|
ul
li = todo.item
p = link_to "Edit", edit_todo_path(todo.id)
p = link_to "Delete", todo, :method => :delete
|
35032c02e8e62140bd59528d73482ee08d4ddcc7
|
[
"Slim"
] | 1 |
Slim
|
bruxelles86/rails-todo
|
145ffd409b878fc31e4a36cabff8aea1fb8ff85e
|
384d8830c5829a59ac5b6b09504d1c44bce5b01a
|
refs/heads/master
|
<repo_name>chibimami6/Homework2<file_sep>/assets/js/app2.js
// // let swiper = new swiper(".swiper-container", {
// // })
// let target = $("#scroll").offset()top;
// console.log(123);
// // サンプルがクリックされたら
// $("h1").on("click", function () {
// console.log(123);
// })
// // oがscrollの位置まで移動する
// スクロールしたら
$(window).on("scroll", function () {
// console.log(123);
// サンプルを消す
// $("h1").animate({ opacity: 0 }, 1500);
// クラス名をはずす
$("#scroll").removeClass("hide");
// ターゲットになる要素の位置
let now = $(window).scrollTop()
let target = $("#scroll").offset().top;
// 画面の高さを取得
let hight = window.innerHeight;
console.log(neight)
console.log(now);
if(now > target - 200) {
console.log("超えました");
$("#scroll").removeClass("hide");
}
})
|
9fcda2a75f6ff6faa60c449bd09934ea25d85402
|
[
"JavaScript"
] | 1 |
JavaScript
|
chibimami6/Homework2
|
159573e2fd4cd893c31626bca338418a345621cc
|
7e981e4cf5808a79abdd4824cb3ed1c78d1b3034
|
refs/heads/master
|
<repo_name>Prakash5bisht/Text-Detection-App-Android<file_sep>/settings.gradle
include ':app'
rootProject.name='Text Detection'
<file_sep>/app/src/main/java/com/example/textdetection/MainActivity.java
package com.example.textdetection;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.FirebaseApp;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button openCam, openGallery;
private final static int REQUEST_OPEN_CAM = 4;
private final static int REQUEST_OPEN_GALLERY = 5;
private FirebaseVisionTextRecognizer textRecognizer;
FirebaseVisionImage image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseApp.initializeApp(this);
openCam = findViewById(R.id.camera_button);
openGallery = findViewById(R.id.gallery);
openCam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePicture.resolveActivity(getPackageManager()) != null){
startActivityForResult(takePicture,REQUEST_OPEN_CAM);
}
}
});
openGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Intent choosePicture = new Intent(Intent.ACTION_PICK);
choosePicture.setType("image/*");
startActivityForResult(choosePicture, REQUEST_OPEN_GALLERY);
}
else{
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},0);
}
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode == REQUEST_OPEN_CAM && resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap)bundle.get("data");
recognizeText(bitmap);
}
else if(requestCode == REQUEST_OPEN_GALLERY && resultCode == RESULT_OK ){
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
recognizeText(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void recognizeText(Bitmap bitmap) {
try {
image = FirebaseVisionImage.fromBitmap(bitmap);
textRecognizer = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
} catch (Exception e) {
e.printStackTrace();
}
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
@Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
String resultText = firebaseVisionText.getText();
if(resultText.isEmpty()){
Toast.makeText(getApplicationContext(),"No Text Recognized",Toast.LENGTH_SHORT);
}
else{
Intent intent = new Intent(MainActivity.this,ResultActivity.class);
intent.putExtra(TextRecognition.RESULT_TEXT,resultText);
startActivity(intent);
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT);
}
});
}
}
|
6d5c3cbd7e1299f383cf4adb8e9d46cd9f875782
|
[
"Java",
"Gradle"
] | 2 |
Java
|
Prakash5bisht/Text-Detection-App-Android
|
1a098a194e233bef57d302f4a7de1e1f622a2968
|
4024e7f7ee9b2bccf8956461ae666923265713d2
|
refs/heads/master
|
<repo_name>rfaroul/reactGoogleMaps<file_sep>/src/app.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Map from './components/Map'
import Places from './components/Places'
import superagent from 'superagent' //makes api call from foursquare. uses promises
//this is the App component
//think of components as HTML tags, roughly speaking
class App extends Component { //ideally, component should only do one thing
//after invoke a class, React expects a render method and triggers a lifecycle that can be hooked into lifecycle methods
//as soon as render method is called, componentDidMount function is called. this is where you access the DOM and manipulate/fetch data
componentDidMount(){ //should see this in console. successfully overrides the lifecycle method
console.log("component did mount");
}
//spit out HTML here
//the only way to call the render method is when state changes
render(){
//pass location variable as center property to the map (below in the div)
const location = { //Times Square
lat: 40.7575285,
lng: -73.9884469
}
//an array of pins for the locations. to start just rendering one marker, so have one object. then have to pass this as a property called markers to the map HTML element
const markers = [
{
location: {
lat: 40.7575285,
lng: -73.9884469
}
}
]
return(
<div>
This is the REACT APP!
<div style={{width:300, height:600, background:'red'}}>
<Map center={location} markers={markers} />
<Places />
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
|
184cfe52995502ecd4589bf677e2bd5677b69aa5
|
[
"JavaScript"
] | 1 |
JavaScript
|
rfaroul/reactGoogleMaps
|
053b6f681bd85a35ed63a8b7fdfcbb4b35e4ee3e
|
9e24016e041010f5d24be9fb8ae9b82bd77b73ea
|
refs/heads/master
|
<repo_name>Angular2ProjectsByS/SchoolSystem<file_sep>/src/app/constants/UserType.ts
export enum UserType {
STUDENT,
PARENT,
TEACHER,
TUTOR,
ADMIN
}<file_sep>/src/app/service/global/request/http-client.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Jsonp } from '@angular/http';
import { Constants } from '@app/constants/constants';
@Injectable()
export class HttpClient {
constructor(private http: Http) {}
private addAuthorizationToHeaders(headers: Headers){
let accessToken = localStorage.getItem(Constants.Token);
headers.append('Authorization', accessToken);
headers.append('Access-Control-Allow-Origin', '*');
}
private createAuthorizationHeader(): Headers{
let headers = new Headers();
let accessToken = localStorage.getItem(Constants.Token);
headers.append('Authorization', accessToken);
headers.append('Access-Control-Allow-Origin', '*');
return headers;
}
public get(url) {
let headers = this.createAuthorizationHeader();
return this.http.get(url, {headers: headers});
}
public post(url, body) {
let headers = this.createAuthorizationHeader();
headers.append("Content-Type", "application/json");
return this.http.post(url, JSON.stringify(body), {headers: headers});
}
public delete(url) {
let headers = this.createAuthorizationHeader();
return this.http.delete(url, {headers: headers});
}
}<file_sep>/src/app/component/admin/pages/prefixes/admin-prefix-edit/admin-prefix-edit.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminPrefixEditComponent } from '@app/component/admin/pages/prefixes/admin-prefix-edit/admin-prefix-edit.component';
describe('AdminPrefixEditComponent', () => {
let component: AdminPrefixEditComponent;
let fixture: ComponentFixture<AdminPrefixEditComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AdminPrefixEditComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdminPrefixEditComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/component/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import {LoginService } from '@app/service/login.service';
import { Constants } from '@app/constants/constants';
import * as JwtDecode from "jwt-decode";
import { UserType } from '@app/constants/UserType';
import { PageNavigator } from "@app/service/PageNavigator";
@Component({
selector: 'app-login',
providers: [PageNavigator],
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
private credentials = {'username':'', 'password':''};
private loggedIn: boolean;
private isLoginError : boolean;
private loginErrorMsg : string;
constructor(private loginService: LoginService, private pageNavigator : PageNavigator) {
this.checkAdminIsLogged();
this.checkLoginError();
}
checkAdminIsLogged() {
console.log("check admin is logged");
if (localStorage.getItem(Constants.IsUserLogged) == null) {
this.loggedIn = false;
console.log("Ustawiam użytkownika na zalogowanego");
}
else {
this.loggedIn = true;
console.log("Witamy użytkownika");
}
}
checkLoginError() {
console.log("check login errors");
if (localStorage.getItem(Constants.LogginErrorMsg) == null || localStorage.getItem(Constants.LogginErrorMsg) == '') {
this.isLoginError = false;
}
else {
console.log("Wystąpiły błędy logowania");
this.isLoginError = true;
this.loginErrorMsg = localStorage.getItem(Constants.LogginErrorMsg);
}
}
onSubmit() {
console.log("Wysyłam żądanie logowania.");
this.loginService.login(this.credentials).toPromise().then(
res => {
//console.log(res);
let body = JSON.parse(JSON.parse((JSON.stringify(res['_body']))));
let decodedToken = JwtDecode(body.token);
console.log("Decoded token: ");
console.log(decodedToken["scopes"]);
let userTypes: UserType[] = this.parseRoles(decodedToken["scopes"]);
console.log("UserTypes: ");
for (let userType of userTypes) {
console.log(userType);
}
localStorage.setItem(Constants.Token, body.token);
localStorage.setItem(Constants.RefreshToken, body.refreshToken);
localStorage.setItem(Constants.Roles, JSON.stringify(userTypes))
this.pageNavigator.navigateToUserPanel(userTypes)
},
err => {
let message = "";
if (err.status == 401) {
console.log("Request Logowania zakończony niepowodzeniem");
message = "Logowanie nieudane. Błędne dane logowania.";
console.log(message);
}
else if (err.status < 200 || err.status >= 300) {
console.log("Request Logowania zakończony niepowodzeniem");
message = "Błąd serwera. Spróbuj jeszcze raz.";
console.log(message);
}
localStorage.setItem(Constants.LogginErrorMsg, message);
if (localStorage.getItem(Constants.IsUserLogged)) {
localStorage.removeItem(Constants.IsUserLogged);
}
location.reload();
}
);
}
parseRoles(roles): UserType[] {
let userTypes: UserType[] = [];
for (let role of roles) {
userTypes.push(UserType["" + role]);
}
return userTypes;
}
ngOnInit() {
}
}
<file_sep>/src/app/service/RolePageAccessChecker.ts
import { UserType } from "@app/constants/UserType"
import { Constants } from "@app/constants/constants"
export class RolePageAccessChecker {
checkAccesForPage(userType: UserType) : void {
let loggedUserTypes: Array<UserType> = JSON.parse(localStorage.getItem(Constants.Roles));
console.log(loggedUserTypes);
}
}<file_sep>/src/app/pipe/phone-number.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'phoneNumber'
})
export class PhoneNumberPipe implements PipeTransform {
transform(tel: any, args?: any): any {
var value = tel.toString().trim().replace("/^\+/", "");
if (value.match("/[^0-9]/")) {
return tel;
}
let phoneResult : string = '';
switch (value.length) {
case 9:
for (let i = 0; i < value.length; i += 3) {
phoneResult += value.slice(i, i + 3);
if (i < 6) {
phoneResult += " ";
}
console.log(value.slice(i, i + 3));
}
break;
default:
return tel;
}
console.log("Finalny result: " + phoneResult);
return phoneResult;
}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule, Http } from '@angular/http';
import { LoginService } from '@app/service/login.service';
import { UserService } from '@app/service/user.service';
import { HttpClient } from '@app/service/global/request/http-client';
import { RestService } from '@app/service/global/request/rest-service.service';
import { routing } from '@app/app.routing';
import { AppComponent } from '@app/app.component';
import { LoginComponent } from '@app/component/login/login.component';
import { PhoneNumberPipe } from '@app/pipe/phone-number.pipe';
import { AdminMainPageComponent } from '@app/component/admin/main-page/admin-main-page.component';
import { AdminOptionsComponent } from '@app/component/admin/pages/admin-options/admin-options.component';
import { AdminClassesComponent } from '@app/component/admin/pages/admin-nav-cards/admin-classes/admin-classes.component';
import { AdminPrefixesComponent } from '@app/component/admin/pages/prefixes/admin-prefixes-main/admin-prefixes.component';
import { SearchBarComponent } from '@app/component/common/search-bar/search-bar.component';
import { MessageBannerComponent } from '@app/component/common/message-banner/message-banner.component';
import { TwoButtonsModalComponent } from '@app/component/common/two-buttons-modal/two-buttons-modal.component';
import { AdminPrefixesAddComponent } from '@app/component/admin/pages/prefixes/admin-prefixes-add/admin-prefixes-add.component';
import { AdminPrefixEditComponent } from '@app/component/admin/pages/prefixes/admin-prefix-edit/admin-prefix-edit.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
PhoneNumberPipe,
AdminMainPageComponent,
AdminOptionsComponent,
AdminClassesComponent,
AdminPrefixesComponent,
SearchBarComponent,
MessageBannerComponent,
TwoButtonsModalComponent,
AdminPrefixesAddComponent,
AdminPrefixEditComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing
],
providers: [
LoginService,
UserService,
HttpClient,
RestService
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/component/common/message-banner/message-banner.component.ts
import { Component, OnInit, Input, OnChanges } from '@angular/core';
import { BannerMessageInfo } from '@app/model/view/banner-message-info';
declare var $: any;
@Component({
selector: 'app-message-banner',
templateUrl: './message-banner.component.html',
styleUrls: ['./message-banner.component.css']
})
export class MessageBannerComponent implements OnInit, OnChanges {
display : boolean = false;
@Input() banerInfo : BannerMessageInfo;
constructor() { }
ngOnInit() {
}
ngOnChanges() {
console.log("Wykryto zmiany w ErrorBannerComponent");
if (this.banerInfo) {
console.log("Ustawiam display na true");
this.display = true;
console.log("message: " + this.banerInfo.message);
this.changeStyle();
}
else {
console.log("Ustawiam display na false");
this.display = false;
}
}
private changeStyle() {
$("#message-content").removeClass(function(index, className) {
return (className.match(/(^|\s)alert-\S+/g) || []).join(' ');
});
$("#message-content").addClass(this.banerInfo.alertStyle);
}
}
<file_sep>/src/app/model/view/banner-message-info.ts
import { Constants } from "@app/constants/constants";
export class BannerMessageInfo {
message: string;
alertStyle: any;
setAll(message: string, alertStyle: any) {
this.message = message;
this.alertStyle = alertStyle;
}
}<file_sep>/src/app/component/admin/pages/prefixes/admin-prefixes-main/admin-prefixes.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { RestService } from '@app/service/global/request/rest-service.service';
import { Prefix } from '@app/model/school-classes/details/prefix';
import { ModalData } from '@app/model/view/ModalData';
import { URLS } from '@app/constants/urls';
import { TwoButtonsModalComponent } from '@app/component/common/two-buttons-modal/two-buttons-modal.component';
import { ResultRequest } from '@app/model/request/result-request';
import { Constants } from '@app/constants/constants';
import { BannerMessageInfo } from '@app/model/view/banner-message-info';
declare var $ : any;
@Component({
selector: 'app-admin-prefixes',
templateUrl: './admin-prefixes.component.html',
styleUrls: ['./admin-prefixes.component.css']
})
export class AdminPrefixesComponent implements OnInit {
noPrefixes: boolean = true;
banerInfo: BannerMessageInfo;
prefixes : Prefix[] = [];
modalData : ModalData;
prefixToDeletePosition : number;
showAddForm : boolean = false;
private editingPrefixIndex : number = -1;
@ViewChild("twoButtonsModal") twoButtonsModal: TwoButtonsModalComponent;
constructor(private restService : RestService) {
this.initModalData();
this.loadAllPrefixes();
}
ngOnInit() {
}
private initModalData():void {
this.modalData = new ModalData();
this.modalData.title = "";
this.modalData.body = "";
this.modalData.url = "";
}
private async loadAllPrefixes() {
let url = URLS.prefixes.getAll;
let resultRequestSet = await this.restService.get<Prefix>(url);
if (resultRequestSet.responseCode == 200) {
this.prefixes = resultRequestSet.result;
}
console.log("loadAllPrefixes: Sprawdzam kod odpowiedzi.");
this.checkResponseCode(resultRequestSet);
this.checkPrefixesExists(resultRequestSet);
}
showDeleteModal(index) {
this.setupModalData(index);
this.prefixToDeletePosition = index;
this.twoButtonsModal.showModal();
}
private checkResponseCode(requestResult : ResultRequest) {
if (requestResult.responseCode >= 400) {
console.log("checkResponseCode: Mamy błąd powyżej 400");
console.log("Code: " + requestResult.responseCode);
this.noPrefixes = true;
this.setProperMessageBanerContent(requestResult, Constants.prefixes.loading.failure, false);
}
else {
this.noPrefixes = false;
}
}
private checkPrefixesExists(resultRequest) {
console.log("checkPrefixesExists");
if (resultRequest.responseCode == 200) {
console.log("checkPrefixesExists: kod 200");
if (resultRequest.result.length == 0) {
this.noPrefixes = true;
this.banerInfo = new BannerMessageInfo();
this.banerInfo
.setAll(
Constants.prefixes.loading.noPrefixes,
Constants.ALERT_STYLES.ALERT_WARNING
);
}
}
}
private setupModalData(index) {
console.log("setupModalData");
this.modalData.body = "Czy napewno chcesz usunąć prefix \""
+ this.prefixes[index].name
+ "\"? ";
this.modalData.title = "Usuwanie prefiksu \"" + this.prefixes[index].name + "\"";
}
async deletePrfixRequest() {
console.log("deletePrfixRequest()");
let url = URLS.prefixes.deleteOne + "/" + this.prefixes[this.prefixToDeletePosition].id;
let response = await this.restService.delete(url);
console.log("Sprawdzam kod błędu " + response.responseCode);
this.setProperMessageBanerContent(response, Constants.prefixes.delete.failure, true);
if (response.responseCode == 200) {
this.loadAllPrefixes();
}
}
private setProperMessageBanerContent(requestResult : ResultRequest, errorString: string, showSuccess : boolean) {
console.log("admin-prefix: setProperMessage");
let banerInfo = new BannerMessageInfo();
if (requestResult.responseCode == 200) {
if (showSuccess) {
console.log("kod 200");
banerInfo = new BannerMessageInfo();
banerInfo
.setAll(
Constants.REQUEST_SUCCESS_MESSAGE,
Constants.ALERT_STYLES.ALERT_SUCCESS
);
this.banerInfo = banerInfo;
}
}
else if (requestResult.responseCode >= 400 && requestResult.responseCode < 500) {
console.log("Błąd 400");
banerInfo = new BannerMessageInfo();
banerInfo
.setAll(
errorString + Constants.MESSAGE_ERROR_400,
Constants.ALERT_STYLES.ALERT_DANGER);
this.banerInfo = banerInfo;
}
else if (requestResult.responseCode >= 500) {
console.log("setProperMessageBannerContent: ustawiam bannerInfo na błąd dla 500");
console.log("No prefixes: " + this.noPrefixes);
console.log(this.prefixes);
banerInfo = new BannerMessageInfo();
banerInfo
.setAll(
errorString + Constants.MESSAGE_ERROR_500,
Constants.ALERT_STYLES.ALERT_DANGER);
this.banerInfo = banerInfo;
}
}
showAddSetMessageResult(banerInfo) {
console.log("Rezultat zbioru: ");
console.log(banerInfo);
this.banerInfo = banerInfo;
}
editSectionNew(i) {
if (this.editingPrefixIndex < 0) {
this.editingPrefixIndex = i;
}
else if (this.editingPrefixIndex == i) {
this.editingPrefixIndex = -1;
}
else {
this.editingPrefixIndex = i;
}
}
}
<file_sep>/src/app/service/user.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { User } from "@app/model/user";
@Injectable()
export class UserService {
constructor(private http: Http) { }
getAllRoles() {
let url = "/api/admin/role/all";
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append("authorization", localStorage.getItem("Token"));
return this.http.get(url, {headers: headers});
}
addUser(user: User) {
let url = "/api/admin/user/add";
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append("authorization", localStorage.getItem("Token"));
console.log(JSON.stringify(user));
return this.http.post(url, JSON.stringify(user), {headers: headers});
}
}
<file_sep>/src/app/component/admin/pages/prefixes/admin-prefixes-add/admin-prefixes-add.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { RestService } from '@app/service/global/request/rest-service.service';
import { Prefix } from '@app/model/school-classes/details/prefix';
import { URLS } from '@app/constants/urls';
import { Constants } from '@app/constants/constants';
import { BannerMessageInfo } from '@app/model/view/banner-message-info';
import { ResponseMessages } from '@app/model/view/response-messages';
import { MessageBannerService } from '@app/service/global/request/message-banner.service';
@Component({
selector: 'app-admin-prefixes-add',
templateUrl: './admin-prefixes-add.component.html',
styleUrls: ['./admin-prefixes-add.component.css']
})
export class AdminPrefixesAddComponent implements OnInit {
private prefixesToSend : Array<string> = [];
actualPrefixName : string;
validationMessage : string;
responseMessages : ResponseMessages;
@Output() showMessageResultTrigger: EventEmitter<BannerMessageInfo> = new EventEmitter<BannerMessageInfo>();
constructor(private restService: RestService, private responseService: MessageBannerService) {
this.setResponseMessages();
}
ngOnInit() {
}
setResponseMessages() {
this.responseMessages = new ResponseMessages();
this.responseMessages.code200 = Constants.prefixes.add.success;
this.responseMessages.code400 = Constants.prefixes.add.failure + " " + Constants.MESSAGE_ERROR_400;
this.responseMessages.code500 = Constants.prefixes.add.failure + " " + Constants.MESSAGE_ERROR_500;
}
addPrefixToSet() {
let prefixName = this.actualPrefixName.trim();
if (this.checkPrefixName(prefixName)) {
this.validatePrefixName(prefixName);
this.prefixesToSend.push(prefixName);
this.actualPrefixName = "";
if (this.validationMessage !== "") {
this.validationMessage = null;
}
}
else {
this.removeLastSpaceFromPrefix();
}
}
checkPrefixName(name) {
let isValidName = true;
if (this.prefixesToSend.indexOf(name) != -1) {
isValidName = false;
this.validationMessage = Constants.prefixes.validation.prefixExists;
}
else if (!this.validatePrefixName(name)){
isValidName = false;
this.validationMessage = Constants.prefixes.validation.prefixExists;
}
return isValidName;
}
private removeLastSpaceFromPrefix() {
this.actualPrefixName = this.actualPrefixName.substring(0, this.actualPrefixName.length - 1);
}
validatePrefixName(name) {
var pattern = /^[a-z]+$/g;
return pattern.test(name);
}
removePrefixFromSet(i) {
this.prefixesToSend.splice(i, 1);
}
async sendPrefixes() {
let requestResult = null;
if (this.prefixesToSend.length > 0) {
this.sendPrefixCollection();
}
else {
this.sendOnePrefix();
}
}
async sendPrefixCollection() {
let prefixes = this.wrapPrefixesNamesToClasses();
let requestResult = await this.restService.add(URLS.prefixes.addSet, prefixes);
console.log("requestResult: ");
console.log(requestResult);
this.responseService.checkRespone(requestResult, this.showMessageResultTrigger, this.responseMessages);
if (requestResult.responseCode == 200) {
this.prefixesToSend = [];
}
}
async sendOnePrefix() {
let requestResult= null;
if (this.validatePrefixName(this.actualPrefixName)) {
let prefix = new Prefix();
prefix.name = this.actualPrefixName;
requestResult = await this.restService.add(URLS.prefixes.addOne, prefix);
this.responseService.checkRespone(requestResult, this.showMessageResultTrigger, this.responseMessages);
this.clearActualPrefixName(requestResult.responseCode);
}
else {
this.validationMessage = "Nazwa prefiksu posiada nieprawidłowy format.";
}
}
clearActualPrefixName(code) {
if (code == 200) {
this.actualPrefixName = "";
}
}
wrapPrefixesNamesToClasses(): Array<Prefix> {
let prefixes : Array<Prefix> = [];
for (let prefixName of this.prefixesToSend) {
let prefix = new Prefix();
prefix.name = prefixName;
prefixes.push(prefix);
}
return prefixes;
}
}
<file_sep>/src/app/service/login.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class LoginService {
constructor(private http : Http) { }
login(credentials) {
let url = "/rest/api/auth/login";
let headers = new Headers();
headers.append('Content-Type', 'application/json');
console.log(JSON.stringify(credentials));
return this.http.post(url, JSON.stringify(credentials), {headers: headers});
}
}
<file_sep>/src/app/component/common/two-buttons-modal/two-buttons-modal.component.ts
import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { ModalData } from '@app/model/view/ModalData';
declare var $: any;
@Component({
selector: 'app-two-buttons-modal',
templateUrl: './two-buttons-modal.component.html',
styleUrls: ['./two-buttons-modal.component.css']
})
export class TwoButtonsModalComponent implements OnInit {
@Input() modalData: ModalData;
@Output() requestTrigger : EventEmitter<any> = new EventEmitter<any>();
constructor() {
}
startAcceptActions() {
this.emitRequestEvent();
this.closeModal();
}
emitRequestEvent() {
console.log("TwoButtonsModalComponent: emitRequstEvent");
console.log("Wysyłam trigger");
this.requestTrigger.emit(null);
}
closeModal() {
$("#messageModal").modal('hide');
}
showModal() {
$("#messageModal").modal('show');
}
ngOnInit() {
}
}
<file_sep>/src/app/service/global/request/rest-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@app/service/global/request/http-client';
import { ResultRequestSet } from '@app/model/request/result-request-set';
import { ResultRequest } from '@app/model/request/result-request';
@Injectable()
export class RestService {
constructor(private httpClient : HttpClient) { }
async get<T>(url:string) : Promise<ResultRequestSet<T>> {
let resultRequestSet = new ResultRequestSet<T>();
await this.httpClient.get(url).toPromise().then(
res => {
resultRequestSet.setAll(res, true);
},
err => {
resultRequestSet.setAll(err, false);
}
);
return resultRequestSet;
}
async delete(url) : Promise<ResultRequest> {
let requestResult: ResultRequest = new ResultRequest();
await this.httpClient.delete(url).toPromise().then(
res => {
requestResult.setAll(res.status, true);
},
err => {
requestResult.setAll(err.status, false);
}
);
return requestResult;
}
async add(url, body) : Promise<ResultRequestSet<string>> {
let requestResultSet = new ResultRequestSet<string>();
await this.httpClient.post(url, body).toPromise().then(
res => {
requestResultSet.setAll(res, true);
},
err => {
requestResultSet.setAll(err, false);
}
);
return requestResultSet;
}
async update(url, body) : Promise<ResultRequestSet<string>> {
let requestResultSet = new ResultRequestSet<string>();
await this.httpClient.post(url, body).toPromise().then(
res => {
requestResultSet.setAll(res, true);
},
err => {
requestResultSet.setAll(err, false);
}
);
return requestResultSet;
}
}
<file_sep>/src/app/messages/prefix-update-message.ts
import { ResponseMessages } from "@app/model/view/response-messages";
import { Constants } from "@app/constants/constants";
export class PrefixUpdateMessage extends ResponseMessages {
constructor() {
super();
this.code200 = Constants.prefixes.update.success;
this.code400 = Constants.prefixes.update.failure;
this.code500 = Constants.prefixes.update.failure;
}
}<file_sep>/src/app/model/request/result-request-set.ts
import { ResultRequest } from "@app/model/request/result-request";
export class ResultRequestSet<T> extends ResultRequest {
result: T[];
setAll(response, success) {
console.log(response);
try {
this.result = <T[]> response.json();
}
catch (Exception) {
this.result = response._body;
}
this.success = success;
this.responseCode = response.status;
}
}<file_sep>/src/app/app.routing.ts
import { ModuleWithProviders } from "@angular/core";
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from '@app/component/login/login.component';
import { AdminMainPageComponent } from '@app/component/admin/main-page/admin-main-page.component';
import { AdminOptionsComponent } from "@app/component/admin/pages/admin-options/admin-options.component";
import { AdminClassesComponent } from "@app/component/admin/pages/admin-nav-cards/admin-classes/admin-classes.component";
import { AdminPrefixesComponent } from '@app/component/admin/pages/prefixes/admin-prefixes-main/admin-prefixes.component';
const appRoutes: Routes = [
{
path: '',
redirectTo: '/login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
},
{
path: "admin",
component: AdminMainPageComponent,
children: [
{
path: '',
redirectTo: '/admin/options',
pathMatch: 'full'
},
{
path: 'options',
component: AdminOptionsComponent
},
{
path: 'classes',
component: AdminClassesComponent
},
{
path: 'prefixes-class',
component: AdminPrefixesComponent
}
]
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);<file_sep>/src/app/model/role.ts
export class Role {
roleId = 0;
name = "";
}<file_sep>/src/app/service/global/request/message-banner.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '@app/constants/constants';
import { BannerMessageInfo } from '@app/model/view/banner-message-info';
import { ResponseMessages } from '@app/model/view/response-messages'
@Injectable({
providedIn: 'root'
})
export class MessageBannerService {
constructor() { }
checkRespone(requestResult, eventEmitter, messages : ResponseMessages) {
console.log("Sprawdzam błędy");
console.log(requestResult);
let banerInfo = new BannerMessageInfo();
banerInfo.alertStyle = Constants.ALERT_STYLES.ALERT_DANGER;
console.log(requestResult.responseCode);
let message = "";
if (requestResult.responseCode == 200) {
message = messages.code200;
banerInfo.alertStyle = Constants.ALERT_STYLES.ALERT_SUCCESS;
}
else if (requestResult.responseCode >= 400 && requestResult.responseCode < 500) {
message = messages.code400 + " " + Constants.MESSAGE_ERROR_400;
if (requestResult.responseCode == 409) {
message += " " + requestResult.result;
}
}
else if (requestResult.responseCode >= 500) {
console.log("Błąd 500");
message = messages.code500 + " " + Constants.MESSAGE_ERROR_500;
}
banerInfo.message = message;
eventEmitter.emit(banerInfo);
}
getResponseMessage(requestResult, messages : ResponseMessages) : string {
let message : string = "";
if (requestResult.responseCode == 200) {
message = messages.code200;
}
else if (requestResult.responseCode >= 400 && requestResult.responseCode < 500) {
message = messages.code400 + " " + Constants.MESSAGE_ERROR_400;
if (requestResult.responseCode == 409) {
message += " " + requestResult.result;
}
}
else if (requestResult.responseCode >= 500) {
console.log("Błąd 500");
message = messages.code500 + " " + Constants.MESSAGE_ERROR_500;
}
return message;
}
}
<file_sep>/src/app/model/user.ts
import { UserRole } from '@app/model/user-role';
export class User {
userId: number;
username: string = "";
password: string = "";
firstName: string = "";
lastName: string = "";
email: string = "";
phone: string = "";
userRoles : UserRole[] = [];
}<file_sep>/src/app/component/common/search-bar/search-bar.component.ts
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-search-bar',
templateUrl: './search-bar.component.html',
styleUrls: ['./search-bar.component.css']
})
export class SearchBarComponent implements OnInit {
constructor() { }
@Output() showAddFormTrigger : EventEmitter<any> = new EventEmitter<any>();
@Output() showAddSetFormTrigger : EventEmitter<any> = new EventEmitter<any>();
ngOnInit() {
$(".search-field").focus(function() {
$(".search-button-img").addClass("rotate-90");
});
$(".search-field").focusout(function() {
$(".search-button-img").removeClass("rotate-90");
});
}
public showAddForm() {
this.showAddFormTrigger.emit();
}
public showAddSetForm() {
this.showAddSetFormTrigger.emit();
}
}
<file_sep>/src/app/component/admin/pages/prefixes/admin-prefix-edit/admin-prefix-edit.component.ts
import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import { Prefix } from "@app/model/school-classes/details/prefix";
import { Constants } from '@app/constants/constants';
import { RestService } from '@app/service/global/request/rest-service.service';
import { MessageBannerService } from '@app/service/global/request/message-banner.service';
import { URLS } from '@app/constants/urls';
import { ResponseMessages } from '@app/model/view/response-messages';
import { PrefixUpdateMessage } from '@app/messages/prefix-update-message';
@Component({
selector: 'app-admin-prefix-edit',
templateUrl: './admin-prefix-edit.component.html',
styleUrls: ['./admin-prefix-edit.component.css']
})
export class AdminPrefixEditComponent implements OnInit {
constructor(private restService : RestService, private responseService : MessageBannerService) {}
actionResultMsg: string = null;
@Input() prefix: Prefix;
newPrefixVersion : Prefix = this.prefix;
@Output() requestSendPrefixToUpdate: EventEmitter<Prefix> = new EventEmitter<Prefix>();
updateHttpMessages : ResponseMessages;
ngOnInit() {
this.newPrefixVersion = { ...this.prefix };
}
setUpdateHttpMessages() {
this.updateHttpMessages
}
async updatePrefix() {
if (this.validatePrefixName(this.newPrefixVersion.name)) {
console.log(this.newPrefixVersion);
let requestResult = await this.restService.update(URLS.prefixes.update, this.newPrefixVersion);
this.actionResultMsg = this.responseService.getResponseMessage(requestResult, new PrefixUpdateMessage());
this.updateLocalPrefixRepresentation(requestResult.responseCode);
}
else {
this.actionResultMsg = Constants.prefixes.validation.failure;
console.log("Prefix nie przeszedł walidacji");
}
}
updateLocalPrefixRepresentation(code: number) {
if (code == 200) {
this.prefix.name = this.newPrefixVersion.name;
}
}
validatePrefixName(name) {
var pattern = /^[a-z]+$/g;
return pattern.test(name);
}
ngOnDestroy() {
console.log("Zniszczono element: admin-prefix-edit.component");
}
}
<file_sep>/src/app/model/request/result-request.ts
export class ResultRequest {
success: boolean;
responseCode: number;
setAll(code, success) {
this.responseCode = code;
this.success = success;
}
}<file_sep>/src/app/service/PageNavigator.ts
import { UserType } from "@app/constants/UserType";
import { Router } from '@angular/router';
import { defaultUrlMatcher } from "@angular/router/src/shared";
import { Injectable } from "@angular/core";
@Injectable()
export class PageNavigator {
public constructor(private router: Router) {}
public navigateToUserPanel(userTypes : Array<UserType>) {
if (userTypes.length > 1) {
this.navigateToUserPanelSelector(userTypes);
}
else {
this.navigateDirectlyToUserPanel(userTypes);
}
}
private navigateDirectlyToUserPanel(userTypes : Array<UserType>) {
switch (userTypes[0]) {
case UserType.ADMIN:
this.router.navigateByUrl('admin');
break;
default:
console.log("Nie ma strony dla takiego typu użytkownika");
}
}
private navigateToUserPanelSelector(userTypes : Array<UserType>) {
}
}<file_sep>/src/app/constants/urls.ts
import { Constants } from "@app/constants/constants";
export class URLS {
static prefixes = {
getOne : Constants.SCH_PREFIX_PREFIX_URL + "/get",
getAll : Constants.SCH_PREFIX_PREFIX_URL + "/get/all",
deleteOne : Constants.SCH_PREFIX_PREFIX_URL + "/delete",
addSet : Constants.SCH_PREFIX_PREFIX_URL + "/add-set",
addOne: Constants.SCH_PREFIX_PREFIX_URL + "/add",
update: Constants.SCH_PREFIX_PREFIX_URL + "/update"
}
}<file_sep>/src/app/constants/constants.ts
import { UserType } from "@app/constants/UserType"
export class Constants {
public static SERVER_ADDRESS: string = "http://localhost:8081/";
public static SERVER_PROXY: string = "/rest/api";
public static LogginErrorMsg: string = "LogginErrorMsg";
public static IsUserLogged: string = "AdminIsLogged";
public static Token: string = "Token";
public static RefreshToken: string = "RefreshToken";
public static Roles = "Roles";
public static SCH_PREFIX_PREFIX_URL: string = Constants.SERVER_PROXY + "/class-prefixex";
public static ALERT_STYLES = {
ALERT_DANGER : "alert-danger",
ALERT_SUCCESS : "alert-success",
ALERT_WARNING : "alert-warning"
}
static prefixes = {
loading: {
failure : "Niepowodzenie w pobraniu prefiksów.",
noPrefixes: "Brak prefiksów w bazie.",
},
delete: {
failure : "Niepowodzenie usunięcia prefiksu."
},
add: {
success: "Dodanie prefiksu/prefiksów zakończone powodzeniem.",
failure: "Niepowodzenie dodania prefiksu/prefiksów.",
},
validation: {
prefixExists: "Prefiks znajduje się już w zbiorze.",
failure: "Nazwa prefiksu posiada nieprawidłowy format."
},
update: {
success: "Aktualizacja prefiksu zokończona powodzeniem.",
failure: "Niepowodzenie w akutalizacji prefiksu."
}
}
public static REQUEST_SUCCESS_MESSAGE = "Czynność zakończona powodzeniem.";
public static MESSAGE_ERROR_PREFIX = "Czynność zakończona niepowodzieniem.";
public static MESSAGE_ERROR_SUFIX = " Proszę spróbować ponownie.";
public static MESSAGE_ERROR_400 = "Błąd aplikacji.";
public static MESSAGE_ERROR_500 = "Błąd serwera.";
// public static LOADING_SCH_PREFIXES_ERROR = "Niepowodzenie w pobraniu prefiksów.";
// public static DELETING_PREFIX_FAILURE_MESSAGE = "Niepowodzenie usunięcia prefiksu.";
// public static NO_SCH_PREFIXES_MESSAGE = "Brak prefiksów w bazie.";
// public static SCH_PREFIXES_ADD_SET_FAILURE_MESSAGE = "Niepowodzenie dodania prefiksu/prefiksów.";
// public static SCH_PREFIXES_ADD_SET_SUCCESS_MESSAGE = "Dodanie prefiksu/prefiksów zakończone powodzeniem.";
// public static SCH_PREFIX_EXISTS_MESSAGE = "Prefiks znajduje się już w zbiorze.";
// public static SCH_PREFIX_VALIDATION_ERROR_MESSAGE = "Nazwa prefiksu posiada nieprawidłowy format.";
// public static SCH_PREFIXES_UPDATE_SUCCESS_MESSAGE = "Aktualizacja prefiksu zokończona powodzeniem.";
// public static SCH_PREFIXES_UPDATE_FAILURE_MESSAGE = "Niepowodzenie w akutalizacji prefiksu.";
}
<file_sep>/src/app/model/view/response-messages.ts
export class ResponseMessages {
code200 : string;
code400 : string;
code500 : string;
}<file_sep>/src/app/component/admin/main-page/admin-main-page.component.ts
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-admin-main-page',
templateUrl: './admin-main-page.component.html',
styleUrls: ['./admin-main-page.component.css']
})
export class AdminMainPageComponent implements OnInit {
constructor() { }
ngOnInit() {
$(document).ready(function(){
$(".dropdown-item").click(function(){
$(".navbar-toggler").click();
});
});
}
}
|
70f3a96ad41f0268644865a0c521ef12a4350096
|
[
"TypeScript"
] | 29 |
TypeScript
|
Angular2ProjectsByS/SchoolSystem
|
78bef62be06201854b12c56b4b7dbd7d75362768
|
5834b6938906fbacd0e832e10d680c8bcc37ccf1
|
refs/heads/master
|
<repo_name>Berial/RxBus<file_sep>/app/src/main/java/xyz/berial/rxbus/RxBus.java
package xyz.berial.rxbus;
import rx.Observable;
import rx.subjects.ReplaySubject;
import rx.subjects.SerializedSubject;
/**
* RxBus
* Created by Berial on 16/5/21.
*/
public class RxBus {
private final SerializedSubject<Object, Object> bus =
new SerializedSubject<>(ReplaySubject.create());
private static RxBus instance;
private RxBus() {}
public static RxBus getInstance() {
if (instance == null) {
synchronized (RxBus.class) {
if (instance == null) {
instance = new RxBus();
}
}
}
return instance;
}
public static void post(Object... objects) {
if (objects == null) return;
for (Object o : objects) {
getInstance().bus.onNext(o);
}
}
public static <T> Observable<T> get(Class<T> eventType) {
return getInstance().bus.ofType(eventType);
}
}
<file_sep>/app/src/main/java/xyz/berial/rxbus/MainActivity.java
package xyz.berial.rxbus;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import rx.functions.Action1;
@SuppressWarnings("all")
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, NextActivity.class));
}
});
RxBus.postSticky("1", "2", "3");
RxBus.getSticky(Integer.class).subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
Log.d(TAG, integer.toString());
}
});
}
}
|
32dfe68494e483a0da0c3e0fe0ead5bd4c39ac27
|
[
"Java"
] | 2 |
Java
|
Berial/RxBus
|
d7e17cd86a0666c468cdda1c9ff9dd7d96cc5359
|
50bf6ddc7772b8132cde798b061abc47dc3cd191
|
refs/heads/master
|
<file_sep>#Clear out leftover stuff from last session
rm(list=ls())
#########################################################################################
#install dependencies
#bioconductor and bioconductor packages
if (! "BiocInstaller" %in% rownames(installed.packages())){
#Check if bioconductor is already installed
source("https://bioconductor.org/biocLite.R")
biocLite()
}
bioconductor_packages<-c("GenomicFeatures", "AnnotationDbi","BSgenome","BSgenome.Hsapiens.UCSC.hg19")
new.BC.packages<-bioconductor_packages[!(bioconductor_packages %in% installed.packages()[,"Package"])]
if (length(new.BC.packages)) {biocLite(new.BC.packages)}
#Normal R packages
list_of_packages<-c("vegan","RColorBrewer","gplots","ggplot2","data.table","parallel")
new.packages<-list_of_packages[!(list_of_packages %in% installed.packages()[,"Package"])]
if (length(new.packages)) {install.packages(new.packages)}
#Load dependencies
for (package in list_of_packages){library(package,character.only = TRUE)}
for (package in bioconductor_packages){library(package,character.only = TRUE)}
####################################################################################
#Setup variables for current working machine
home_dir=dirname(path.expand("~"))
OS_type=.Platform$OS.type
if (OS_type=="windows"){
g_drive="Google Drive"
} else if (OS_type=="unix"){
g_drive="gdrive"
}
project_name="20162017SumSemResearch"
project_dir=file.path(home_dir,g_drive,project_name)
data_directory=file.path(project_dir,"Datasets")
#Loading in data
SNP_data_dir=file.path(data_directory,"SNPDatabases")
GWAS_cat_SNPs=file.path(SNP_data_dir,"gwas_catalog_v1.0-associations_e86_r2016-10-23.tsv")
SNP_data=fread(GWAS_cat_SNPs,sep="\t")
SNP_data=clean_SNP_data(SNP_data)
#Imputing sequences for all of the indiviudals
#I Think I've misunderstood and this is not necessary
#Extracting flanking sequences
flanking_sequences=list()
flanking_offset=100
for (i in 1:nrow(SNP_data)) {
SNP=SNP_data[i,]
chromosomes=trimws(strsplit(SNP$CHR_ID,";")[[1]])
positions=trimws(strsplit(SNP$CHR_POS,";")[[1]])
SNP_names=trimws(strsplit(SNP$SNPS,";")[[1]])
for (j in 1:length(chromosomes)){
chr=paste("chr",chromosomes[j],sep="")
pos=positions[j]
SNP_name=SNP_names[j]
flanking_sequences[[SNP_name]]=paste(getSeq(Hsapiens,chr,position-flanking_offset,position),
getSeq(Hsapiens,chr,position+1,position+flanking_offset),
sep='')
}
}
#Example linked to by Loic
chr <- 'chr19'
position <- 59900243
alleles <- '[T/C]'
offset <- 60
test_sequence <- paste(getSeq(Hsapiens,chr,position-offset,position-1),
alleles,
getSeq(Hsapiens,chr,position+1,position+offset),
sep='')
#Motif discovery on flanking sequences for a specific SNP
#Writing of intermediate file
#Collation of results across entire genome for background dataset
#Plotting of relative frequency of each motif around a SNP
#Plotting of enrichment of motif compared to entire background dataset
#########################################################################
#Functions
#########################################################################
clean_SNP_data<-function(SNP_data,exclude_interations){
'''A function which takes in the original SNP data and then simplify the variable
SNP naming convenients to always have a chromosome ID and position
It also flattens data.table while splitting based on the ; character in the chromosome,positions
and SNP_name columns.
Input: SNP_data - data.table
A data.table of the SNPS from the GWAS catalogue
Output: cleaned_SNP_data - data.table
A flattened and less ambiguous form of the GWAS catalogue'''
SNP_data$UNIQ_ID=(1:nrow(SNP_data))
if (exclude_interactions){
working_SNP_data=SNP_data[!(grepl("x",SNP_data$CHR_ID) | grepl("x",SNP_data$CHR_POS)),]
}
else {
working_SNP_data=SNP_data
}
#Splitting of SNPs of form chrID:Positions
split_data=working_SNP_data[grepl("chr[0-9]{1,}:[0-9]{1,}",working_SNP_data$SNPS),]
#Needs confirmation as to whether the extra characters here are intential or a mistake
split_data$SNPS=gsub("[:-][A-Z]$","",split_data$SNPS)
#I'll just exclude these if I can't confirm there properties.
#splitting SNPs of form
#Extract the problem sequences with no values
missing_info=SNP_data[SNP_data$CHR_ID=="" | SNP_data$CHR_POS=="",]
}
out <- working_SNP_data[, list(CHR_ID=unlist(strsplit(CHR_ID, "(;|; )")),CHR_POS=unlist(strsplit(CHR_POS, "(;|; )")),SNPS = unlist(strsplit(SNPS, "(;|; )")),"STRONGEST SNP-RISK ALLELE" = unlist(strsplit(`STRONGEST SNP-RISK ALLELE`, "(;|; )"))), by=UNIQ_ID]
test_out<-working_SNP_data[,list(CHR_ID=lengths(regmatches(CHR_ID, gregexpr("(;|; )", CHR_ID))),CHR_POS=lengths(regmatches(CHR_POS, gregexpr("(;|; )", CHR_POS))),"STRONGEST SNP-RISK ALLELE"=lengths(regmatches(`STRONGEST SNP-RISK ALLELE`, gregexpr("(;|; )", `STRONGEST SNP-RISK ALLELE`))),SNPS=lengths(regmatches(SNPS, gregexpr("(;|; )", SNPS)))),by=UNIQ_ID]
out_new<-working_SNP_data[out$UNIQ_ID,]
#First
#Imputing sequences for all of the indiviudals
#I Think I've misunderstood and this is not necessary
#Extracting flanking sequences
#Example linked to by Loic
chr <- 'chr19'
position <- 59900243
alleles <- '[T/C]'
offset <- 60
test_sequence <- paste(getSeq(Hsapiens,chr,position-offset,position-1),
alleles,
getSeq(Hsapiens,chr,position+1,position+offset),
sep='')
#Motif discovery on flanking sequences for a specific SNP
#Writing of intermediate file
#Collation of results across entire genome for background dataset
#Plotting of relative frequency of each motif around a SNP
#Plotting of enrichment of motif compared to entire background dataset
<file_sep>#2016-2017 Summer Project
This encapuslates my project work for the 2016-2017 summer with Dr Yengo-Dimbou in Prof. <NAME>'s lab.
The project comes in a few stages. The first is motif discovery near single nucleotide polymorphisms (SNPs).
The second has to do with clustering SNPs and using these clusters to investigate genetic variance.
The project is arrange to have Datasets which are public and private. Only the public datasets are committed.
Analyses contains the R code used to process data and some of the output.
GeneralScripts are just any widely used scripts which I end up using in multiple aspects of the project.
|
6e67dc336ace30d04b62472b2058deaae5769fd0
|
[
"Markdown",
"R"
] | 2 |
Markdown
|
AlexRBaker/2016-2017SumSemProject
|
b2ff6de988af5029aacd85f6e37c3b07b9d4a856
|
24244fc98eb27707737050d9f7e2060ffa8382c4
|
refs/heads/main
|
<file_sep>cho "# personalPortfolio" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/Ishaque-Ahmed/personalPortfolio.git
git push -u origin main
<file_sep>body{
font-family: 'Open Sans', sans-serif;
}
a{
text-decoration: none;
}
p{
text-align: justify;
}
.banner-container{
background-color: #CAD3C8;
}
.banner-content{
background-color: #2C3A47;
}
.navbar-container{
background-color:#182C61;
top: 0;
position: sticky;
z-index: 2;
}
.about-container{
background-color: #16a085;
}
.education-container{
background-color: #CAD3C8;
}
.education-header-color{
color:#c0392b;
}
.education-bg-color{
background-color: #c0392b;
}
.circle{
background-color: #c0392b;
height: 150px;
width: 150px;
border-radius: 50%;
text-align: center;
}
.project-container{
background-color: #3498db;
}
.gallery-container{
background-color: #f39c12;
}
.form-container{
background-color: #34495e;
}
.inner-form{
background-color: #16a085;
}
.btn-per{
color:#ecf0f1;
background-color: #16a085;
padding: 10px 30px!important;
text-align: center;
}
.footer{
background-color: #9b59b6;
}
.foot-circle{
width: 60px;
height: 60px;
border-radius: 50%;
display: inline-block;
background-color: white;
font-size: 40px;
text-align: center;
color: #c0392b;
}
.foot-circle:hover{
color:white;
background-color: #c0392b;
}
|
d68ba54c715c67ee1102632a0487669c1da6b5ac
|
[
"Markdown",
"CSS"
] | 2 |
Markdown
|
Ishaque-Ahmed/personalPortfolio
|
f7d359d23a05d2eeaaef5a52323716cc386faa45
|
05116580f75616844077ef1446e08c0e560b99e6
|
refs/heads/master
|
<file_sep># PointCloudHack
### MILESTONE 1
- Point cloud of Slovenia from Satelite data VUCKO
- Get data from API for Slovenia
- Save data to .txt format:
- x y z R G B
- 0.0 0.0 0.0 255 122 122
- Label 5 locations with spheres -> clickable VUCKO
- ```5 spheres```
- ```respond to click event```
- When click:
- Unload satellite point cloud
- ```Unload point cloud```
- ```Load another point cloud```
- ```Fade to black + loading screen + spawn at starting point```
- Load 1sqkm region in Slovenia
- ```use PointCloud plugin```
- Add surrounding region Satellite data
- ```Concatenate 2 point clouds```
### MILESTONE 2
- Game mechanics
- ```Actor that moves through the scene```
- ```Can shoot```
- ```Shoots AI agents```
- Multi-player VUCKO
|
d63a7bb2394dc202739ccbae0b7c911a20fb69d9
|
[
"Markdown"
] | 1 |
Markdown
|
mirceta/PointCloudHack
|
6b33864f00b782d5116fb2eae2e1198d346b8c8b
|
e8addd893e0da5d78173939e32303155c90646be
|
refs/heads/master
|
<file_sep>class node:
def __init__(self,value=None):
self.value = value
self.next = self
def isEmpty(self):
return self.value == None
def append(self,v): #similar to insertAtEnd
if self.isEmpty():
self.value = v
self.next = self
return
temp = self
while(temp.next != self):
temp = temp.next
newnode = node(v)
temp.next = newnode
newnode.next = self
return
def display(self):
if self.isEmpty():
print("Empty List!!")
return
temp = self
while(temp.next != self):
print(temp.value)
temp = temp.next
print(temp.value)
print(self.value)
return
def insertAtBeginning(self,v):
if self.isEmpty():
self.value = v
self.next = self
return
newnode = node(v)
self.value,newnode.value = newnode.value,self.value
self.next,newnode.next = newnode,self.next
return
def deleteAtEnd(self):
if self.isEmpty():
print("List is Empty!!! Deletion is not possible")
return
if self.next == next:
self.value = None
self.next = None
return
temp = self
while temp.next != self:
temp2 = temp
temp = temp.next
temp2.next = self
return
def deleteAtBeginning(self):
if self.isEmpty():
print("LIst is Empty!! Deletion is not possible")
return
if self.next == self:
self.value = None
self.next = None
return
temp = self
while temp.next != self:
temp = temp.next
self.value = self.next.value
self.next = self.next.next
temp.next = self
return
def deleteSpecificNode(self,v):
if self.isEmpty():
print("List is Empty!! Deletion is not possible!!")
return
if self.value == v:
self.deleteAtBeginning()
return
temp1 = self
while temp1.next != self:
temp2 = temp1
temp1 = temp1.next
if temp1.value == v:
temp2.next = temp2.next.next
return
print("Reached end of the list."+str(v)+" is not found")
return
"""
l = node(50)
l.append(4)
l.append(5)
l.append(6)
l.append(8)
l.append(9)
l.append(10)
l.display()
print("\n")
l.deleteAtEnd()
l.display()
print("\n")
l.deleteAtBeginning()
l.display()
print("\n")
l.deleteSpecificNode(4)
l.display()
"""
<file_sep>class Node:
def __init__(self,data = None,right = None,left = None):
self.data = data
self.right = right
self.left = left
def isEmpty(self):
return (self.data == None)
def addChild(self,data):
if self.isEmpty():
self.data = data
return
temp = self
while(True):
if temp.right == None and temp.left == None:
if data > temp.data:
temp.right = Node(data)
return
if data <= temp.data:
temp.left = Node(data)
return
if data > temp.data:
if temp.right == None:
temp.right = Node(data)
return
temp = temp.right
if data <= temp.data:
if temp.left == None:
temp.left = Node(data)
return
temp = temp.left
def inOrder(self):
temp = self
if temp.left:
temp.left.inOrder()
print(temp.data,sep = " ",end = " ")
if temp.right:
temp.right.inOrder()
def preOrder(self):
temp = self
print(temp.data,sep = " ",end = " ")
if temp.left:
temp.left.preOrder()
if temp.right:
temp.right.preOrder()
def postOrder(self):
temp = self
if temp.left:
temp.left.postOrder()
if temp.right:
temp.right.postOrder()
print(temp.data,sep = " ",end = " ")
"""
l = Node()
l.addChild(10)
l.addChild(4)
l.addChild(12)
l.addChild(3)
l.addChild(5)
l.addChild(11)
l.addChild(13)
l.inOrder()
print()
l.preOrder()
print()
l.postOrder()
print()
"""
<file_sep>class node:
def __init__(self,data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enQueue(self,data):
if self.rear == None:
self.front = self.rear = node(data)
return
self.rear.next = node(data)
self.rear = self.rear.next
def deQueue(self):
if self.front == None:
print("Empty Queue!!Deletion is not possible")
return
self.front = self.front.next
def display(self):
if self.front == None:
print("Empty Queue!!")
return
temp = self.front
while temp.next != None:
print(temp.data)
temp = temp.next
print(temp.data)
return
"""
l = Queue()
l.display()
l.enQueue(4)
l.display()
l.enQueue(5)
l.enQueue(6)
l.enQueue(7)
l.enQueue(8)
print("\n")
l.display()
l.deQueue()
print("\n")
l.display()
l.deQueue()
l.deQueue()
print("\n")
l.display()
"""
<file_sep>class node:
def __init__(self,value = None):
self.value = value
self.next = None
def isempty(self):
return (self.value == None)
def append(self,v): #similar to insertAtEnd
if self.value == None:
self.value = v
return
temp = self
while(temp.next!=None):
temp = temp.next
temp.next = node(v)
return
def display(self):
if self.value == None:
print("Empty List")
return
if self.next == None:
print(self.value)
return
temp = self
while(temp.next!= None):
print(temp.value)
temp = temp.next
print(temp.value)
return
def insertAtBeginning(self,v):
if self.isempty():
self.value = v
return
newnode = node(v)
(self.value ,newnode.value) = (newnode.value,self.value)
(self.next,newnode.next) = (newnode,self.next)
return
def insertAtEnd(self,v): #similar to append
if self.isempty():
self.value = v
return
temp = self
while(temp.next != None):
temp = temp.next
newnode = node(v)
temp.next = newnode
return
def deleteAtBeginning(self):
if self.isempty():
print("List is empty!!!")
return
if self.next == None:
self.value = None
return
else:
self.value = self.next.value
self.next = self.next.next
return
def deleteAtEnd(self):
if self.isempty():
print("List is Empty!!Deletion is not possible")
return
if self.next == None:
self.value = None
return
temp1 = self
while(temp1.next!= None):
temp2 = temp1
temp1 = temp1.next
temp2.next = None
return
def deleteSpecificNode(self,v):
if self.isempty():
print("List is Empty!!Deletion is not possible")
return
if self.next == None:
if self.value == v:
self.value = None
return
temp1 = self
while(temp1.next != None):
temp2 = temp1
temp1 = temp1.next
if temp1.value == v:
temp2.next = temp2.next.next
return
print("reached end of the list."+str(v)+" is not found")
return
"""
l = node(5)
l.append(4)
l.append(3)
l.append(2)
l.append(1)
l.display()
print("\n")
l.insertAtBeginning(6)
l.insertAtEnd(7)
l.display()
print("\n")
l.deleteAtBeginning()
l.display()
print("\n")
l.deleteAtEnd()
l.display()
print("\n")
l.deleteSpecificNode(3)
l.deleteSpecificNode(9)
print("\n")
l.display()
"""
<file_sep>from collections import deque
q = deque([])
def enQueue(x):
q.append(x)
def deQueue():
if len(q) == 0:
print("Empty Queue!! Deletion is not possible")
return
q.popleft()
def display():
if len(q) == 0:
print("Empty Queue!!")
return
for i in q:
print(i,end=" ")
print()
<file_sep># DataStructures-python
This repository contains code for different Data Structures in python
<file_sep>l = []
def push(x):
l.append(x)
def pop():
if len(l) == 0:
print("List is empty!! Deletion is not possible")
return
l.pop()
def display():
if len(l) == 0:
print("List is empty")
return
for i in list(reversed(l)):
print(i)
<file_sep>class Node:
def __init__(self,data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self,data):
if self.head == None:
self.head = Node(data)
return
newnode = Node(data)
newnode.next = self.head
self.head = newnode
return
def pop(self):
if self.head == None:
print("Stack is empty!! Deletion is not possible")
return
self.head = self.head.next
return
def display(self):
if self.head == None:
print("Stack in empty!!!")
return
temp = self.head
while temp.next != None:
print(temp.data)
temp = temp.next
print(temp.data)
return
|
ca3fcd819c13634f71382d30ecda769f07373d7f
|
[
"Markdown",
"Python"
] | 8 |
Markdown
|
KishoreArani/DataStructures-python
|
091db7b86a00a889277108a96db3e6a318c92288
|
a7092a3d76a8ee18e35e15c5ff2f4babc420aa0d
|
refs/heads/master
|
<repo_name>Young-Devin/Young-Devin-Bicycle_theft_Group_Group1_section_section1COMP309Proj<file_sep>/group2_final_project_data_modeling.py
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 12:21:19 2019
@author: devin
"""
<file_sep>/group2_final_project.py
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 12:20:10 2019
@author: group1
"""
## 1 Data Exploration
## 1a - Load and describe data elements (columns) provide descriptions & types with values of each element.-
##use pandas, numpy and any other python packages
import pandas as pd
import os
path = "C:/Users/devin/Documents/COMP309/Bicycle_theft_Group_Group1_section_section1COMP309Proj/data"
filename = 'Bicycle_Thefts.csv'
fullpath = os.path.join(path,filename)
data_group1_b = pd.read_csv(fullpath,sep=',')
print(data_group1_b.columns.values)
print(data_group1_b.shape)
print(data_group1_b.describe())
print(data_group1_b.dtypes)
## Set pd to display all columns, as there is only 26 columns.
pd.set_option('display.max_columns',26)
## Print the first 20 rows of the data_group1_b dataframe
print(data_group1_b.head(20))
## Print the first 30 and last 30 rows of the data_group1_b dataframe
print(data_group1_b.describe)
## explore all the suspicious columns that may seem unique, all identified unique columns will be dropped from dataframe
print(data_group1_b['Index_'][0:50].value_counts())
print(data_group1_b['Hood_ID'][0:50].value_counts())
print(data_group1_b['ObjectId'][0:50].value_counts())
print(data_group1_b['event_unique_id'][0:50].value_counts())
##Get the count of all unique values for the Primary_Offence column
print(data_group1_b['Primary_Offence'].value_counts())
##Get the count of all unique values for the Bike_Type column
print(data_group1_b['Bike_Type'].value_counts())
##Get the count of all unique values for the Bike_Make column
print(data_group1_b['Bike_Make'].value_counts())
##Get the count of all unique values for the Bike_Colour column
print(data_group1_b['Bike_Colour'].value_counts())
##Get the count of all unique values for the Location_Type column
print(data_group1_b['Location_Type'].value_counts())
##Get the count of all unique values for the Division column
print(data_group1_b['Division'].value_counts())
## Checking the unique value counts for the Neighbourhood column
## Note for Group: there is 141 different values for this column, should we keep it
print(data_group1_b['Neighbourhood'].value_counts())
##Get the count of all unique values for the Occurrence_Day column
print(data_group1_b['Occurrence_Day'].value_counts())
##Get the count of all unique values for the Occurrence_Time column
print(data_group1_b['Occurrence_Time'].value_counts())
##Get the count of all unique values for the Premise_Type column
print(data_group1_b['Premise_Type'].value_counts())
## Dropping all unique and repetitive variables that are useless for predictive analysis
data_group1_b = data_group1_b.drop(['X','Y','Index_', 'ObjectId', 'event_unique_id','Occurrence_Date', 'City', 'Bike_Model', 'Bike_Make', 'Neighbourhood', 'Occurrence_Time'], axis=1)
print(data_group1_b.shape)
## 1b - Statistical assessments including means, averages, correlations
##Check the basic statistic details of all numeric columns
print(data_group1_b.describe())
## Print just the mean of all numeric values
print(data_group1_b.mean())
## Print the correlation of the entire dataframe
print(data_group1_b.corr())
#Check the mean of all numeric columns grouped by Bike_Type
print(data_group1_b.groupby('Bike_Type').mean())
## 1c - Missing data evaluations–use pandas, numpy and any other python packages
##examine the count statistic of all numeric variables
print(data_group1_b.count())
## Missing data evaluation using the isnull method
print(data_group1_b.isnull().sum())
## 1d - Graphs and visualizations–use pandas, matplotlib, seaborn, numpy and any other python packages,
## also you can use power BI desktop.
## Plotting the frequency of Bike Thefts in each month using a histogram
import matplotlib.pyplot as plt
data_group1_b.Occurrence_Month.hist()
plt.title('Histogram of Month Of Occurence')
plt.xlabel('Month Of Occurence')
plt.ylabel('Frequency')
## Visualization using Seaborn
import seaborn as sns
sns.distplot(data_group1_b['Occurrence_Month'], rug=True, hist=False)
##sns.pairplot(data_group1_b)
## 2a - Data transformations includes missing data handling, categorical data management,
## data normalization and standardizations as needed.
##missing data handling
##Get the count of all unique values for the Status column
print(data_group1_b['Status'].value_counts())
##delete all UNKNOWN values from the Status column
data_group1_b = data_group1_b[data_group1_b.Status != 'UNKNOWN']
##Print all rows from 100 to 149 of column Cost_of_Bike
data_group1_b['Cost_of_Bike'][100:150]
## Get the Cost_of_Bike average
print(data_group1_b['Cost_of_Bike'].mean())
## Get the mean of the Cost_of_Bike based on its Bike_Type
data_group1_b.groupby('Bike_Type').mean().Cost_of_Bike
## Replace missing values in the Cost_of_Bike column with its average based on Bike_Type
data_group1_b['Cost_of_Bike'] = data_group1_b['Cost_of_Bike'].fillna(data_group1_b.groupby('Bike_Type')['Cost_of_Bike'].transform('mean').round(2))
## Print all rows from 100 to 149 of column Cost_of_Bike after filling in the missing results
data_group1_b['Cost_of_Bike'][100:150]
print(data_group1_b['Bike_Model'].unique())
## Replace all categorical missing values with the value 'missing'.
print(data_group1_b.describe())
data_group1_b.fillna("missing",inplace=True)
data_group1_b[100:150]
##if we want to resort to deleting rows with missing values, use the following code
##data_group1_b.dropna(inplace=True)
##categorical data management
cat_vars=['Primary_Offence', 'Location_Type', 'Premise_Type', 'Bike_Type', 'Bike_Colour']
for group1 in cat_vars:
cat_list_group1='group1'+'_'+group1
print(cat_list_group1)
cat_list_group1 = pd.get_dummies(data_group1_b[group1], prefix=group1)
data_group1_b_dummies = data_group1_b.join(cat_list_group1)
data_group1_b = data_group1_b_dummies
# Remove the original columns
cat_vars=['Primary_Offence', 'Location_Type', 'Premise_Type', 'Bike_Type', 'Bike_Colour']
data_group1_b_vars=data_group1_b.columns.values.tolist()
to_keep=[i for i in data_group1_b_vars if i not in cat_vars]
data_group1_b_final=data_group1_b[to_keep]
data_group1_b_final.columns.values
## Prepare for model build
data_group1_b_final_vars=data_group1_b_final.columns.values.tolist()
Y=['Status']
X=[i for i in data_group1_b_final_vars if i not in Y ]
type(Y)
type(X)
## data normalization and standardizations
## 2b - Feature selection–use pandas and sci-kit learn.
from sklearn import datasets
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(solver='lbfgs')
## select 7 features from the RFE model
rfe = RFE(model, 7)
rfe = rfe.fit(data_group1_b_final[X],data_group1_b_final[Y] )
print(rfe.support_)
print(rfe.ranking_)
## Added selected features to X and classifier to Y
cols=[] ## features selected
X=data_group1_b_final[cols]
Y=data_group1_b_final['Status']
## 2c - Training and testing data splits–use numpy, sci-kit learn
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
## 3- Predictive model building
## Use logistic regression and decision trees–use sci-kit learn
from sklearn import linear_model
from sklearn import metrics
clf_lr_group1 = linear_model.LogisticRegression(solver='lbfgs')
clf_lr_group1.fit(X_train, Y_train)
predicted = clf_lr_group1.predict(X_test)
print (predicted)
#4-Check model accuracy
print (metrics.accuracy_score(Y_test, predicted))
|
cc50b4b0bd7571de1847cb2db6ecf0dd1f8b868f
|
[
"Python"
] | 2 |
Python
|
Young-Devin/Young-Devin-Bicycle_theft_Group_Group1_section_section1COMP309Proj
|
023b9de7d0a7e63c013fc1c080e96b02337a0e1e
|
c089a7aae16b3d7a627521c2e4f1a078caadb5f9
|
refs/heads/master
|
<file_sep># haskell-za-studente-kodovi
Prateći kodovi koji se koriste u knjizi "Haskell za studente"
|
93cdbc8b99c52533b8d00d6d5b8d46c9303a4869
|
[
"Markdown"
] | 1 |
Markdown
|
mzdv/haskell-za-studente-kodovi
|
de8a1b6172f38e180156d18fb1fa4b4160142dcc
|
affe485f33ff1a139288fdc964face9feeaedf60
|
refs/heads/master
|
<file_sep># hello-world
no description.
nothing to write about myself.
oh! i love to travel.
|
524ab5cfe026314ed64f87fd7abe508c181157c5
|
[
"Markdown"
] | 1 |
Markdown
|
gurbaajsingh94/hello-world
|
46f5adccfc10ef37ccb7d845715bfc5230ed170e
|
86c29a2a747cc09b1b0ec0a5f4a9fbec62663ffb
|
refs/heads/master
|
<file_sep># A Recipe for a Redis RPM on CentOS
Perform the following on a build box as a regular user.
## Create an RPM Build Environment
Install rpmdevtools from the [EPEL][epel] repository:
sudo yum install rpmdevtools
rpmdev-setuptree
## Install Prerequisites for RPM Creation
sudo yum groupinstall 'Development Tools'
## Download Redis
wget http://download.redis.io/releases/redis-2.6.16.tar.gz
mv redis-2.6.16.tar.gz ~/rpmbuild/SOURCES/
## Get Necessary System-specific Configs
git clone git://github.com/bluerail/redis-centos.git
cp redis-centos/conf/* ~/rpmbuild/SOURCES/
cp redis-centos/spec/* ~/rpmbuild/SPECS/
## Build the RPM
cd ~/rpmbuild/
rpmbuild -ba SPECS/redis.spec
The resulting RPM will be:
~/rpmbuild/RPMS/x86_64/redis-2.6.16-1.{arch}.rpm
## Credits
Based on the `redis.spec` file from <NAME>.
Maintained by [<NAME>](<EMAIL>)
[EPEL]: http://fedoraproject.org/wiki/EPEL#How_can_I_use_these_extra_packages.3F
|
1dfe7d8a0548e4a25ada63afbf0aedab65a83899
|
[
"Markdown"
] | 1 |
Markdown
|
DanielRedOak/redis-centos
|
8b5e95d4a9c7de4e241a8b3618fef255b05afafc
|
4ba4d3b0c5653c2445257dfa1eca84a09989b7b8
|
refs/heads/main
|
<file_sep>- 👋 Hi, I’m @kesavanvickey
- 👀 I’m interested in IOT, ML, AI and Cloud
- 🌱 I’m currently learning IOT and Cloud Concepts
- 💞️ I’m looking to collaborate for open source and new technologies
- 📫 Reach me via linkedin https://www.linkedin.com/in/kesavanvickey
<!---
kesavanvickey/kesavanvickey is a ✨ special ✨ repository because its `README.md` (this file) appears on your GitHub profile.
You can click the Preview link to take a look at your changes.
--->
|
765b6bcad04366d81593c100ba4da36eb76e8a5f
|
[
"Markdown"
] | 1 |
Markdown
|
kesavanvickey/kesavanvickey
|
ad081088c0947b6b4424faf7f39407d12061a43a
|
2571c5e6826423cb0d2fdd9ecb2135efc9156fae
|
refs/heads/main
|
<repo_name>DemianMtz1/recetari.o-client<file_sep>/src/components/Navbar/index.tsx
import axios from 'axios';
import jwt from 'jsonwebtoken';
import { useEffect, useState } from 'react';
import {
Link, useHistory, useLocation
} from 'react-router-dom';
import { MenuNav } from '../MenuNav';
import './styles/navbarStyles.scss';
interface Visibility {
isVisible: boolean
}
type User = {
firstName: string,
lastName: string,
avatar: string,
email: string,
username: string,
password: string,
role: string
}
const defaultUser: User = {
firstName: "",
lastName: "",
avatar: "",
email: "",
username: "",
password: "",
role: ""
}
const Navbar = () => {
const location = useLocation();
const history = useHistory();
const [user, setUser] = useState(defaultUser);
const [visibility, setVisibility] = useState<Visibility>({
isVisible: false
});
const handleLogOut = () => {
window.localStorage.removeItem('rttoken');
history.push('/');
window.location.reload();
}
useEffect(() => {
const getProfile = async () => {
try {
const token = window.localStorage.getItem('rttoken');
if (!token) {
return;
}
const today: Date = new Date();
const tokenDecoded: any = jwt.decode(token);
if (tokenDecoded.exp * 1000 < today.getTime()) {
window.localStorage.removeItem('rttoken');
return;
}
const options = {
headers: {
authorization: window.localStorage.getItem('rttoken')
}
}
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/users/profile', options);
setUser(data.data.user);
} catch (error) {
console.error(error);
}
}
getProfile()
}, []);
return (
<>
{
location.pathname === '/log-in' || location.pathname === '/register' ?
<nav className="w-100 p-3 d-flex justify-content-between custom-nav fixed-pos">
<h1 onClick={() => history.push('/')}>Recetar<span>.io</span></h1>
<span className="icon fas fa-bars d-md-none" onClick={() => setVisibility({ isVisible: !visibility.isVisible })}></span>
{
visibility.isVisible && (
<ul className="nav-menu p-4 d-md-none">
<div className="align-self-end">
<span className="icon-sm fas fa-times text-white" onClick={() => setVisibility({ isVisible: !visibility.isVisible })} ></span>
</div>
{
(user.email || user.role) ?
<MenuNav
user={user}
isMobile={true}
handleLogOut={handleLogOut}
/>
:
<>
<li><Link to="/log-in">Inicia sesion</Link></li>
<button type="button" className="primary-button" onClick={() => history.push('/register')}>Registrate!</button>
</>
}
</ul>
)
}
<ul className="d-none d-md-flex">
{
(user.email || user.role) ?
<MenuNav
user={user}
handleLogOut={handleLogOut}
/>
:
<>
<li><Link to="/log-in">Inicia sesion</Link></li>
<button type="button" className="primary-button" onClick={() => history.push('/register')}>Registrate!</button>
</>
}
</ul>
</nav>
:
<nav className='w-100 p-3 d-flex justify-content-between custom-nav'>
<h1 onClick={() => history.push('/')}>Recetar<span>.io</span></h1>
<span className="icon fas fa-bars d-md-none" onClick={() => setVisibility({ isVisible: !visibility.isVisible })}></span>
{
visibility.isVisible && (
<ul className="nav-menu p-4 d-md-none">
<div className="align-self-end">
<span className="icon-sm fas fa-times text-white" onClick={() => setVisibility({ isVisible: !visibility.isVisible })} ></span>
</div>
{
(user.email || user.role) ?
<MenuNav
user={user}
isMobile={true}
handleLogOut={handleLogOut}
/>
:
<>
<li><Link to="/log-in">Inicia sesion</Link></li>
<button type="button" className="primary-button" onClick={() => history.push('/register')}>Registrate!</button>
</>
}
</ul>
)
}
<ul className="d-none d-md-flex">
{
(user.email || user.role) ?
<MenuNav
user={user}
handleLogOut={handleLogOut}
/>
:
<>
<li><Link to="/log-in">Inicia sesion</Link></li>
<button type="button" className="primary-button" onClick={() => history.push('/register')}>Registrate!</button>
</>
}
</ul>
</nav>
}
</>
)
}
export default Navbar<file_sep>/src/components/IngredientList/index.tsx
export const IngredientList = (prop: any) => {
const { ingredient, handleRemoveIngredient } = prop;
return (
<>
<li key={ingredient.NOOID} className="list-group-item d-flex justify-content-between align-items-center">
<div className="d-flex flex-column">
<p className="fw-bold m-0 mb-2">{`${ingredient.ingredientName} x${ingredient.quantity}`}</p>
<p className="text-muted m-0">{`${ingredient.ingredientQuantity} ${ingredient.ingredientMeasure}`}</p>
</div>
<span className="fas fa-times icon-sm" onClick={() => handleRemoveIngredient(ingredient)}>
</span>
</li>
</>
)
}
<file_sep>/src/components/RecetaList/index.tsx
import { useHistory } from "react-router-dom";
export const RecetaList = (props: any) => {
const history = useHistory()
const { recipe, categories, handleDeleteRecipe } = props;
const showCategory = (categories: any[], recipe: any) => {
const filteredCategories: any = categories.find((category) => category._id === recipe.categoryId)
return " " + filteredCategories.title;
}
return (
<div className="list-group-item" >
<div className="d-flex w-100 justify-content-between">
<h5 className="fw-bold mb-1">{recipe.title}</h5>
<div className="d-flex">
<span className="fas fa-edit px-3 text-secondary pointer" onClick={() => history.push(`/editar-receta/${recipe._id}`)}></span>
<span className="fas fa-times-circle text-danger pointer" onClick={() => handleDeleteRecipe(recipe._id)}></span>
</div>
</div>
<p className="mb-1 fst-italic">{recipe.description}</p>
<p className="fw-bold">Categoria: </p>
<small className="text-muted">{showCategory(categories, recipe)}</small>
<div className="w-100">
<button className="my-3 primary-button" onClick={() => history.push(`/ver-receta/${recipe._id}`)}>
Ver mas...
</button>
</div>
</div>
)
}
<file_sep>/src/components/MenuNav/index.tsx
import {
Link,
} from 'react-router-dom';
export const MenuNav = (props: any) => {
if (props.isMobile) {
return (
<>
<li><Link to="/crear-recetas">Agrega receta</Link></li>
<li><Link to="/tus-recetas">Tus recetas</Link></li>
{
props.user.role === 'admin' ?
<>
<li><Link to="/admin/categorias">Categorias</Link></li>
<li><Link to="/admin/medidas">Medidas</Link></li>
</>
:
null
}
<li onClick={props.handleLogOut}>Cerrar Sesión</li>
</>
)
}
return (
<>
<li><Link to="/crear-recetas">Agrega receta</Link></li>
<li><Link to="/tus-recetas">Tus recetas</Link></li>
{
props.user.role === 'admin' ?
<>
<li><Link to="/admin/categorias">Categorias</Link></li>
<li><Link to="/admin/medidas">Medidas</Link></li>
</>
:
null
}
<button type="button" className="primary-button" onClick={props.handleLogOut}>Cerrar Sesión</button>
</>
)
}
<file_sep>/src/screens/TusCategorias/index.tsx
import axios from 'axios';
import jwt from 'jsonwebtoken'
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { toast } from 'react-toastify';
import chefsitoMirar from '../../assets/img/chef-categorias.svg';
type Category = {
_id: string,
title: string
}
export const TusCategorias = () => {
const history = useHistory();
const [categories, setCategories] = useState([]);
const [isDeleted, setIsDeleted] = useState(false);
useEffect(() => {
const getCategories = async () => {
try {
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/categories');
setCategories(data.data.categories)
} catch (error: any) {
toast.error(error.response.data.message);
}
}
getCategories()
return () => {
setCategories([])
}
}, [isDeleted]);
const handleDeleteCategory = async (id: string) => {
try {
const token = window.localStorage.getItem('rttoken');
const options = {
headers: {
authorization: token
}
}
const { data } = await axios.delete(`https://recetario-app-edmv.herokuapp.com/categories/${id}`, options);
toast.success('Categoria eliminada correctamente :D');
setIsDeleted(true);
setIsDeleted(false);
} catch (error: any) {
toast.error(error.response.data.message);
}
}
const ListData = (props: any) => {
return (
<div className="list-group-item" >
<div className="d-flex w-100 justify-content-between">
<h5 className="fw-bold mb-1">{props.category.title}</h5>
<div className="d-flex">
<span className="fas fa-times-circle text-danger pointer" onClick={() => props.handleDeleteCategory(props.category._id)}></span>
</div>
</div>
</div>
)
}
return (
<div className="container container-fluid">
<div className="row pb-5">
<div className="col-12 col-md-5 d-flex flex-column justify-content-center text-header-wrapper">
<h1>Tus categorias</h1>
<p>En esta seccion podras encontrar todas las categorias que haz agregado como administrador.</p>
</div>
<div className="col-12 col-md-7 mt-4">
<div className="img-header-wrapper">
<img src={chefsitoMirar} alt="chefsito" className="w-50" />
</div>
</div>
</div>
<div className="row">
<div className="col-12 text-white">
<div className="w-100 bg-primary-color p-2 px-3 rounded">
<div className="w-100 d-flex justify-content-between align-items-center">
<h4>Tus categorias</h4>
<span className="icon-sm text-white fas fa-plus-circle pointer" onClick={() => history.push('/admin/crear-categoria')}></span>
</div>
</div>
<div className="w-100 list-group text-dark mt-3">
{
!categories ?
null
:
categories.map((category: Category) => <ListData category={category} handleDeleteCategory={handleDeleteCategory} />)
}
</div>
</div>
</div>
</div>
)
}
<file_sep>/src/components/routers/Routes.tsx
import {
Switch,
Route
} from 'react-router-dom';
import { AgregarCategorias } from '../../screens/AgregarCategorias';
import { AgregaReceta } from '../../screens/AgregaReceta';
import { AgregarMedidas } from '../../screens/AgregarMedidas';
import { EditarReceta } from '../../screens/EditarReceta';
import { Home } from '../../screens/Home';
import { Login } from '../../screens/LogIn';
import { Register } from '../../screens/Register';
import { TusCategorias } from '../../screens/TusCategorias';
import { TusMedidas } from '../../screens/TusMedidas';
import { TusRecetas } from '../../screens/TusRecetas';
import { VerReceta } from '../../screens/VerReceta';
export const Routes = () => {
return (
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/log-in" exact>
<Login />
</Route>
<Route path="/register" exact>
<Register />
</Route>
<Route path="/crear-recetas" exact>
<AgregaReceta />
</Route>
<Route path="/tus-recetas" exact>
<TusRecetas />
</Route>
<Route path="/ver-receta/:id" exact>
<VerReceta />
</Route>
<Route path="/editar-receta/:id" exact>
<EditarReceta />
</Route>
<Route path="/admin/categorias" exact>
<TusCategorias />
</Route>
<Route path="/admin/crear-categoria" exact >
<AgregarCategorias />
</Route>
<Route path="/admin/medidas" exact>
<TusMedidas />
</Route>
<Route path="/admin/crear-medidas" exact>
<AgregarMedidas />
</Route>
</Switch>
)
}
<file_sep>/src/screens/AgregarCategorias/index.tsx
import axios from "axios";
import jwt from 'jsonwebtoken';
import leerReceta from '../../assets/img/chef-categorias.svg';
import { toast } from "react-toastify";
import React, { useEffect, useState } from 'react';
import { useHistory } from "react-router-dom";
type User = {
firstName: string,
lastName: string,
avatar: string,
email: string,
username: string,
password: string,
role: string
}
const defaultUser: User = {
firstName: "",
lastName: "",
avatar: "",
email: "",
username: "",
password: "",
role: ""
}
type Category = {
title: string
}
const defaultCategory: Category = {
title: ""
}
export const AgregarCategorias = () => {
const [user, setUser] = useState(defaultUser);
const [category, setCategory] = useState(defaultCategory);
const history = useHistory();
useEffect(() => {
const getUser = async () => {
try {
const token = window.localStorage.getItem('rttoken');
if (!token) {
return;
}
const today: Date = new Date();
const tokenDecoded: any = jwt.decode(token);
if (tokenDecoded.exp * 1000 < today.getTime()) {
window.localStorage.removeItem('rttoken');
return;
}
const options = {
headers: {
authorization: window.localStorage.getItem('rttoken')
}
}
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/users/profile', options);
if (data.data.user.role !== 'admin') {
history.push('/');
toast.error('Ruta protegida, no cuentas con los permisos...')
return;
}
setUser(data.data.user);
} catch (error: any) {
toast.error(error.response.data.message)
}
}
getUser()
return () => {
setUser(defaultUser)
}
}, []);
const handleChangeTitle = (ev: React.ChangeEvent<HTMLInputElement>) => setCategory({ ...category, [ev.target.name]: ev.target.value })
const handleSubmitCategory = async (ev: React.FormEvent<HTMLFormElement>) => {
ev.preventDefault();
try {
const token = window.localStorage.getItem('rttoken') || "";
if (!category.title) {
toast.error('Upsss... Olvidaste nombrar a tu categoria');
return;
}
if (user.role !== 'admin') {
history.push('/');
toast.error('Ruta protegida, no cuentas con los permisos...')
return;
}
const options = {
headers: {
authorization: token
}
}
await axios.post('https://recetario-app-edmv.herokuapp.com/categories', category, options);
toast.success('Categoria agregada de manera satisfactoria :D');
setCategory(defaultCategory);
} catch (error) {
toast.error(error.response.data.message);
}
}
return (
<div className="container container-fluid ver-receta-container">
<div className="row">
<div className="col-12 wrapper-section">
<section className="bg-primary-color pt-4 shadow">
<div className="w-100 p-4 shadow ver-receta shadow">
<form onSubmit={handleSubmitCategory}>
<h3 className="mb-3 fw-bold text-center">Agrega las categorias</h3>
<div className="mb-3">
<label className="text-muted mb-2">Nombre de la categoria:</label>
<input
className="mt-2"
placeholder="E.g. Comida china..."
type="text"
name="title"
value={category.title}
onChange={handleChangeTitle}
/>
</div>
<button className="primary-button w-100">Agregar categoria</button>
</form>
</div>
</section>
</div>
</div>
<img className="d-none d-md-block img-abs-receta" src={leerReceta} alt="leer-receta" />
</div >
)
}
<file_sep>/src/screens/Register/index.tsx
import axios from "axios";
import jwt from 'jsonwebtoken';
import chefsito from '../../assets/img/chef-receta-4.svg';
import { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { toast } from 'react-toastify';
import './styles/registerStyles.scss';
type User = {
firstName: string,
lastName: string,
avatar: string,
email: string,
username: string,
password: string,
role: string
}
const defaultUser: User = {
firstName: "",
lastName: "",
avatar: "",
email: "",
username: "",
password: "",
role: "user"
}
export const Register = () => {
const history = useHistory();
const [user, setUser] = useState(defaultUser);
useEffect(() => {
const validateToken = () => {
const token = window.localStorage.getItem('rttoken');
if (!token) {
return;
}
const today: Date = new Date();
const tokenDecoded: any = jwt.decode(token);
if (tokenDecoded.exp * 1000 < today.getTime()) {
window.localStorage.removeItem('rttoken');
return;
}
history.push('/')
}
validateToken()
}, [])
const handleChangeUser = (ev: React.ChangeEvent<HTMLInputElement>) => setUser({ ...user, [ev.target.name]: ev.currentTarget.value })
const handleSubmitUser = async (ev: React.FormEvent<HTMLFormElement>) => {
ev.preventDefault();
try {
const { firstName, lastName, avatar, email, username, password, role } = user;
if (!firstName || !lastName || !avatar || !email || !username || !password || !role) {
toast.error('Upss... No se pueden enviar campos vacios.');
return;
}
const { data } = await axios.post('https://recetario-app-edmv.herokuapp.com/users/signup', user);
toast.success('Cuenta registrada!');
window.localStorage.setItem('rttoken', data.data.token);
setUser(defaultUser);
history.push('/');
} catch (error) {
toast.error(error.response.data.message);
}
}
return (
<>
<div className="w-100 d-flex content-register">
<section className="">
<div>
<h1>Recetar<span>.io</span></h1>
<p>"Ser cocinero es un gran honor. Llamarse "chef", una pequeña huachafería"<span> - <NAME></span></p>
</div>
</section>
<section className="p-4 d-flex flex-column justify-content-center">
<form className="p-4 shadow" onSubmit={handleSubmitUser}>
<h3 className="text-center mb-4">Crea tu cuenta</h3>
<div className="mb-4">
<label className="form-label">Primer nombre:</label>
<input
className="form-control"
placeholder="Eg. Clarence..."
type="text"
name="firstName"
value={user.firstName}
onChange={handleChangeUser}
/>
</div>
<div className="mb-4">
<label className="form-label">Apellido paterno:</label>
<input
className="form-control"
placeholder="Eg. Smith..."
type="text"
name="lastName"
value={user.lastName}
onChange={handleChangeUser}
/>
</div>
<div className="mb-4">
<label className="form-label">Foto de perfil:</label>
<input
className="form-control"
placeholder="Eg. https://googleimages.com/image-123..."
type="text"
name="avatar"
value={user.avatar}
onChange={handleChangeUser}
/>
</div>
<div className="mb-4">
<label className="form-label">Email:</label>
<input
className="form-control"
placeholder="Eg. <EMAIL>..."
type="email"
name="email"
value={user.email}
onChange={handleChangeUser}
/>
</div>
<div className="mb-4">
<label className="form-label">Nombre de usuario:</label>
<input
className="form-control"
placeholder="Eg. ChefHernan122..."
type="text"
name="username"
value={user.username}
onChange={handleChangeUser}
/>
</div>
<div className="mb-4">
<label className="form-label">Password:</label>
<input
className="form-control"
placeholder="Como minimo 6 caracteres"
type="password"
name="password"
value={user.password}
onChange={handleChangeUser}
/>
</div>
<button type="submit" className="primary-button w-100 mb-4">Registrarse</button>
<div className="mb-4 d-flex justify-content-end w-100 create-section">
<span onClick={() => history.push('/log-in')}>Ya tengo cuenta.</span>
</div>
</form>
<img src={chefsito} alt="chefsito-img" className="abs-img" />
</section>
</div>
</>
)
}
<file_sep>/src/screens/AgregaReceta/index.tsx
import { useEffect, useState } from 'react';
import axios from 'axios';
import jwt from 'jsonwebtoken';
import { toast } from 'react-toastify';
import { IngredientList } from '../../components/IngredientList';
import './styles/agReceta.scss';
type Recipe = {
authorId: string,
title: string,
description: string,
categoryId: string,
ingredients: any[],
procedure: string
}
type Ingredient = {
NOOID: string,
ingredientName: string,
quantity: number,
ingredientQuantity: number,
ingredientMeasure: string
}
const defaultRecipe: Recipe = {
authorId: "",
title: "",
description: "",
categoryId: "",
ingredients: [],
procedure: ""
}
const defaultIngredient: Ingredient = {
NOOID: "",
ingredientName: "",
quantity: 0,
ingredientQuantity: 0,
ingredientMeasure: ""
}
export const AgregaReceta = () => {
const [categories, setCategories] = useState<any>();
const [measures, setMeasures] = useState<any>();
const [ingredients, setIngredients] = useState<any[]>([]);
const [recipe, setRecipe] = useState(defaultRecipe);
const [ingredient, setIngredient] = useState(defaultIngredient);
const [total, setTotal] = useState({});
useEffect(() => {
const getCategories = async () => {
try {
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/categories');
setCategories(data.data.categories)
} catch (error) {
toast.error(error.response.data.message);
}
}
getCategories()
return () => {
setCategories([])
}
}, [])
useEffect(() => {
const getMeasures = async () => {
try {
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/measures');
setMeasures(data.data.measures)
} catch (error) {
toast.error(error.response.data.message);
}
}
getMeasures()
return () => {
setMeasures([])
}
}, [ingredients]);
useEffect(() => {
const getTotal = () => {
if (!measures || !ingredients) {
return;
}
let totalHashMap: any = {};
measures.forEach((measure: any) => {
totalHashMap = {
...totalHashMap,
[measure.measureType]: {
total: 0
}
}
})
ingredients.forEach((ingredient: any) => {
for (const key in totalHashMap) {
if (key === ingredient.ingredientMeasure) {
totalHashMap[key].total += (ingredient.ingredientQuantity * ingredient.quantity)
}
}
})
setTotal(totalHashMap)
}
getTotal();
return () => {
setTotal({})
}
}, [measures, ingredients])
const handleChangeRecipe = (ev: React.ChangeEvent<HTMLInputElement>) => setRecipe({ ...recipe, [ev.target.name]: ev.target.value })
const handleChangeIngredient = (ev: React.ChangeEvent<HTMLInputElement>) => setIngredient({ ...ingredient, [ev.target.name]: ev.target.value })
const handleSubmitRecipe = async (ev: React.FormEvent<HTMLFormElement>) => {
ev.preventDefault();
try {
const token = window.localStorage.getItem('rttoken') || "";
const options = {
headers: {
authorization: token
}
}
const user: any = jwt.decode(token);
if (!recipe.categoryId || !recipe.description || !recipe.procedure || !recipe.title) {
console.log(recipe);
toast.error("Upss... Se te olvido llenar los campos.");
return
}
if (ingredients.length <= 0) {
toast.error("Upss... Se te ha olvidado agregarle ingredientes a tu receta.");
return
}
const newRecipe = {
...recipe,
ingredients: ingredients,
authorId: user.id
}
const { data } = await axios.post('https://recetario-app-edmv.herokuapp.com/recipes', newRecipe, options);
setRecipe(defaultRecipe);
console.log(data);
toast.success("La receta se agrego de manera exitosa.");
} catch (error) {
toast.error(error.response.data.message);
}
}
const handleSubmitIngredient = async (ev: React.FormEvent<HTMLFormElement>) => {
ev.preventDefault();
try {
if (!ingredient.ingredientMeasure || !ingredient.ingredientName || !ingredient.ingredientQuantity || !ingredient.quantity) {
toast.error("Upss... Se te olvido llenar los campos.");
return
}
const today = new Date().getTime();
const newIngredient: Ingredient = {
...ingredient,
NOOID: today.toLocaleString()
}
setIngredients([...ingredients, newIngredient]);
setIngredient(defaultIngredient);
toast.success('Ingrediente añadido correctamente.')
} catch (error) {
toast.error(error.message);
}
}
const handleRemoveIngredient = (ingredient: Ingredient) => {
const filteredIngredients = ingredients.filter((ingredientFiltered: Ingredient) => ingredientFiltered.NOOID !== ingredient.NOOID);
setIngredients(filteredIngredients);
}
return (
<div className="container container-fluid content-agrega">
<div className="row d-flex justify-content-center ">
<div className="col-12 col-md-8 mb-4">
<form className="peso-content w-100 p-4 shadow" onSubmit={handleSubmitRecipe}>
<h3 className="mb-3 fw-bold">Receta</h3>
<div className="mb-3">
<label>Nombre de la receta:</label>
<input
className="mt-2"
placeholder="E.g. Pollo asado rico"
type="text"
name="title"
onChange={handleChangeRecipe}
/>
</div>
<div className="mb-3">
<label>Descripción:</label>
<input
className="mt-2"
placeholder="E.g. Receta de pollo asado..."
type="text"
name="description"
onChange={handleChangeRecipe}
/>
</div>
<div className="mb-3">
<label className="w-100">Categoria:</label>
<select className="w-100" name="categoryId" value={recipe.categoryId} onChange={(ev: React.ChangeEvent<HTMLSelectElement>) => setRecipe({ ...recipe, [ev.target.name]: ev.target.value })}>
{
!recipe.categoryId ? (<option value="">-- Selecciona una categoria --</option>) : null
}
{
!categories ? null : categories.map((category: any) => <option key={category._id} value={category._id}>{category.title}</option>)
}
</select>
</div>
<div className="mb-3">
<label>Procedimiento:</label>
<textarea
className="mt-2"
placeholder="Eg. Se necesitara mover 10 tipos de pollos..."
name="procedure"
value={recipe.procedure}
onChange={(ev: React.ChangeEvent<HTMLTextAreaElement>) => setRecipe({ ...recipe, [ev.target.name]: ev.target.value })}
/>
</div>
<button className="primary-button">Agregar receta</button>
</form>
</div>
<div className="col-12 col-md-4 mb-3">
<form className="peso-content shadow p-4" onSubmit={handleSubmitIngredient}>
<div className="mb-3">
<h3 className="fw-bold mb-3">Ingredientes:</h3>
<label>Nombre del ingrediente:</label>
<input
className="my-2"
placeholder="Eg. Ojos de pez..."
type="text"
name="ingredientName"
value={ingredient.ingredientName}
onChange={handleChangeIngredient}
/>
<label>Cantidad:</label>
<input
className="my-2"
placeholder="Eg. 2"
type="number"
name="quantity"
value={ingredient.quantity}
onChange={handleChangeIngredient}
/>
<div className="d-flex w-100 align-items-end my-3">
<label className="w-25">Peso:</label>
<div className="w-50 d-flex align-items-end">
<input
className="w-50"
placeholder="Eg. 25"
type="number"
name="ingredientQuantity"
value={ingredient.ingredientQuantity}
onChange={handleChangeIngredient}
/>
<select className="w-50" name="ingredientMeasure" onChange={(ev: React.ChangeEvent<HTMLSelectElement>) => setIngredient({ ...ingredient, [ev.target.name]: ev.target.value })}>
{
!ingredient.ingredientMeasure ? (<option defaultChecked={true} value="">-- Selecciona una categoria --</option>) : null
}
{
!measures ? null : measures.map((measure: any) => <option defaultChecked={true} key={measure._id} value={measure.measureType}>{measure.measureType}</option>)
}
</select>
</div>
</div>
</div>
<div className="d-flex w-100 justify-content-between">
<button className="secondary-button">Añadir ingrediente</button>
</div>
</form>
</div>
<div className="col-12">
<div className="total-ingredientes p-4 shadow">
<h3 className="fw-bold">Total:
{
Object.keys(total).length <= 0 ?
null
:
Object.entries(total).map(([key, value]: any, idx: number) => {
if (value.total > 0) {
return ` ${value.total} ${key} -`
}
})
}
</h3>
<ul className="list-group mt-4">
{
ingredients.map((ingredient: Ingredient, idx) => <IngredientList key={idx} ingredient={ingredient} handleRemoveIngredient={handleRemoveIngredient} />)
}
</ul>
</div>
</div>
</div>
</div>
)
}
<file_sep>/src/screens/VerReceta/index.tsx
import axios from "axios";
import jwt from 'jsonwebtoken';
import logo from '../../assets/img/chefsito.png';
import leerReceta from '../../assets/img/leer-receta.svg'
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { toast } from "react-toastify";
import './styles/verRecetaStyles.scss';
type Recipe = {
_id: string,
title: string,
description: string,
categoryId: string,
ingredients: any[],
procedure: string,
authorId: string
}
type User = {
firstName: string,
lastName: string,
avatar: string,
email: string,
username: string,
password: string,
role: string
}
const defaultUser: User = {
firstName: "",
lastName: "",
avatar: "",
email: "",
username: "",
password: "",
role: ""
}
const defaultRecipe: Recipe = {
_id: "",
title: "",
description: "",
categoryId: "",
ingredients: [],
procedure: "",
authorId: ""
}
export const VerReceta = () => {
const params: any = useParams();
const [recipe, setRecipe] = useState(defaultRecipe);
const [categories, setCategories] = useState<any[]>([]);
const [total, setTotal] = useState({});
const [user, setUser] = useState(defaultUser);
useEffect(() => {
const getRecipeById = async () => {
try {
const { data } = await axios.get(`https://recetario-app-edmv.herokuapp.com/recipes/${params.id}`);
setRecipe(data.data.recipe);
} catch (error) {
console.error(error);
}
}
getRecipeById()
return () => {
setRecipe(defaultRecipe)
}
}, []);
useEffect(() => {
const getTotal = async () => {
try {
if (!recipe._id) {
return;
}
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/measures');
let totalHashMap: any = {};
data.data.measures.forEach((measure: any) => {
totalHashMap = {
...totalHashMap,
[measure.measureType]: {
total: 0
}
}
})
recipe.ingredients.forEach((ingredient: any) => {
for (const key in totalHashMap) {
if (key === ingredient.ingredientMeasure) {
totalHashMap[key].total += (ingredient.ingredientQuantity * ingredient.quantity)
}
}
})
setTotal(totalHashMap);
} catch (error) {
console.error(error);
}
}
getTotal()
return () => {
setTotal({})
}
}, [recipe])
useEffect(() => {
const getCategories = async () => {
try {
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/categories');
setCategories(data.data.categories)
} catch (error) {
toast.error(error.response.data.message);
}
}
getCategories()
return () => {
setCategories([])
}
}, [])
useEffect(() => {
const getUser = async () => {
try {
const token = window.localStorage.getItem('rttoken');
if (!token) {
return;
}
const today: Date = new Date();
const tokenDecoded: any = jwt.decode(token);
if (tokenDecoded.exp * 1000 < today.getTime()) {
window.localStorage.removeItem('rttoken');
return;
}
const options = {
headers: {
authorization: window.localStorage.getItem('rttoken')
}
}
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/users/profile', options);
setUser(data.data.user);
} catch (error) {
toast.error(error.response.data.message)
}
}
getUser()
return () => {
setUser(defaultUser)
}
}, [])
return (
<div className="container container-fluid ver-receta-container">
<div className="row">
<div className="col-12 wrapper-section">
<section className="bg-primary-color pt-5 shadow">
<div className="w-100 p-4 shadow ver-receta">
<div className="img-receta-wrapper">
<img src={logo} alt="logo-pagina" />
<p className="fw-bold text-primary-color">{!user.firstName ? null : user.firstName + ' ' + user.lastName}</p>
</div>
<div className="receta-wrapper mt-3">
<section className="p-2 p-md-4">
<div className="d-flex mb-3 w-100 flex-wrap">
<h3 className="fw-bold">Nombre receta:</h3>
<p>{!recipe.title ? null : recipe.title}</p>
</div>
<div className="d-flex mb-3 w-100 flex-wrap">
<h3 className="fw-bold">Descripción de la receta:</h3>
<p>{!recipe.description ? null : recipe.description}</p>
</div>
<div className="d-flex mb-3 w-100 flex-wrap">
<h3 className="fw-bold">Procedimiento:</h3>
<p>{!recipe.procedure ? null : recipe.procedure}</p>
</div>
<div className="d-flex mb-3 w-100 flex-wrap">
<h3 className="fw-bold">Categoria:</h3>
<p>
{
categories.length <= 0 || !recipe.categoryId ?
null
:
categories.find((category: any) => category._id === recipe.categoryId).title
}
</p>
</div>
</section>
<section className="p-2 p-md-4">
<div className="d-flex flex-column mb-3 w-100 flex-wrap">
<h3 className="fw-bold">Ingredients:</h3>
<ul>
{
recipe.ingredients.length <= 0
?
null
:
recipe.ingredients.map((ingredient: any) => <li className="" key={ingredient._id}><span>{ingredient.ingredientName} {ingredient.ingredientQuantity} {ingredient.ingredientMeasure} </span> <span className="fw-bold text-primary-color"> x{ingredient.quantity}</span></li>)
}
</ul>
<p className="fw-bold">Total Peso:</p>
<p>
{
Object.keys(total).length <= 0 ?
null
:
Object.entries(total).map(([key, value]: any, idx: number) => {
if (value.total > 0) {
return ` ${value.total} ${key} -`
}
})
}
</p>
</div>
</section>
</div>
</div>
</section>
</div>
</div>
<img className="d-none d-md-block img-abs-receta" src={leerReceta} alt="leer-receta" />
</div >
)
}
<file_sep>/src/screens/TusMedidas/index.tsx
import axios from 'axios';
import jwt from 'jsonwebtoken'
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { toast } from 'react-toastify';
import chefsitoMirar from '../../assets/img/chef-measures.svg';
type Measure = {
_id: string,
measureType: string
}
export const TusMedidas = () => {
const history = useHistory();
const [measures, setMeasures] = useState([]);
const [isDeleted, setIsDeleted] = useState(false);
useEffect(() => {
const getMeasures = async () => {
try {
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/measures');
setMeasures(data.data.measures)
} catch (error: any) {
toast.error(error.response.data.message);
}
}
getMeasures()
return () => {
setMeasures([])
}
}, [isDeleted]);
const handleDeleteMeasures = async (id: string) => {
try {
const token = window.localStorage.getItem('rttoken');
const options = {
headers: {
authorization: token
}
}
const { data } = await axios.delete(`https://recetario-app-edmv.herokuapp.com/measures/${id}`, options);
toast.success('Medida eliminada correctamente :D');
setIsDeleted(true);
setIsDeleted(false);
} catch (error: any) {
toast.error(error.response.data.message);
}
}
const ListData = (props: any) => {
return (
<div className="list-group-item" >
<div className="d-flex w-100 justify-content-between">
<h5 className="fw-bold mb-1">{props.measure.measureType}</h5>
<div className="d-flex">
<span className="fas fa-times-circle text-danger pointer" onClick={() => props.handleDeleteMeasures(props.measure._id)}></span>
</div>
</div>
</div>
)
}
return (
<div className="container container-fluid">
<div className="row pb-5">
<div className="col-12 col-md-5 d-flex flex-column justify-content-center text-header-wrapper">
<h1>Tus medidas</h1>
<p>En esta seccion podras encontrar todas las medidas que haz agregado como adminsitrador.</p>
</div>
<div className="col-12 col-md-7 mt-4">
<div className="img-header-wrapper">
<img src={chefsitoMirar} alt="chefsito" className="w-50" />
</div>
</div>
</div>
<div className="row">
<div className="col-12 text-white">
<div className="w-100 bg-primary-color p-2 px-3 rounded">
<div className="w-100 d-flex justify-content-between align-items-center">
<h4>Tus medidas</h4>
<span className="icon-sm text-white fas fa-plus-circle pointer" onClick={() => history.push('/admin/crear-medidas')}></span>
</div>
</div>
<div className="w-100 list-group text-dark mt-3">
{
measures.length === 0 ?
null
:
measures.map((measure: Measure) => <ListData measure={measure} handleDeleteMeasures={handleDeleteMeasures} />)
}
</div>
</div>
</div>
</div>
)
}
<file_sep>/src/App.tsx
import {
BrowserRouter as Router,
} from 'react-router-dom';
import Navbar from './components/Navbar';
import { ToastContainer } from 'react-toastify';
import { Routes } from './components/routers/Routes';
import 'react-toastify/dist/ReactToastify.css';
function App() {
return (
<>
<Router>
<ToastContainer />
<Navbar />
<Routes />
</Router>
</>
);
}
export default App;
<file_sep>/src/screens/Home/index.tsx
import axios from 'axios';
import jwt from 'jsonwebtoken';
import { useHistory } from 'react-router-dom';
import { useEffect, useState } from 'react';
import chefsito from '../../assets/img/chef-receta.svg';
import ceviche from '../../assets/img/chefsito.png';
import './styles/homeStyles.scss';
type User = {
firstName: string,
lastName: string,
avatar: string,
email: string,
username: string,
password: string,
role: string
}
const defaultUser: User = {
firstName: "",
lastName: "",
avatar: "",
email: "",
username: "",
password: "",
role: ""
}
export const Home = () => {
const history = useHistory();
const [user, setUser] = useState(defaultUser);
useEffect(() => {
const getProfile = async () => {
try {
const token = window.localStorage.getItem('rttoken');
if (!token) {
return;
}
const today: Date = new Date();
const tokenDecoded: any = jwt.decode(token);
if (tokenDecoded.exp * 1000 < today.getTime()) {
window.localStorage.removeItem('rttoken');
return;
}
const options = {
headers: {
authorization: window.localStorage.getItem('rttoken')
}
}
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/users/profile', options);
setUser(data.data.user);
} catch (error) {
console.error(error.response.data.message);
}
}
getProfile()
}, [])
const handleGettingStart = () => {
if(user.email){
history.push('/crear-recetas')
return;
}
history.push('/log-in');
}
return (
<>
<div className="container container-fluid">
<div className="row pb-5">
<div className="col-12 col-md-5 d-flex flex-column justify-content-center text-header-wrapper">
<h1>Bienvenidos a Recetar.io</h1>
<p>Aplicación desarrollada para las personas que quieren guardar sus recetas.</p>
<button type="button" className=" primary-button" onClick={handleGettingStart}>Empecemos!</button>
</div>
<div className="col-12 col-md-7 mt-4">
<div className="img-header-wrapper">
<img src={ceviche} alt="chefsito" />
</div>
</div>
</div>
<div className="row py-5 mt-5">
<div className="d-none d-md-block col-12 col-md-6 ">
<div className="img-header-wrapper">
<img src={chefsito} alt="chefsito-1" />
</div>
</div>
<div className="col-12 col-md-6 d-flex justify-content-center flex-column text-section">
<h2>Recetario Online</h2>
<p>Construye tu propio libro culinario de manera completamente gratuita.</p>
</div>
<div className="col-12 d-md-none">
<div className="img-header-wrapper">
<img src={chefsito} alt="chefsito-1" />
</div>
</div>
</div>
<div className="row py-5 mt-5">
<div className="col-12 text-section">
<h2 className="text-center">¿Que se puede hacer?</h2>
</div>
<div className="col-12 col-md-4 mt-5">
<div className="card shadow-sm">
<div className="card-body">
<h5 className="card-title">Agrega tus recetas</h5>
<p className="card-text">Al tener una cuenta en Recetar.io podras crear de manera gratuita la cantidad de recetas que necesites y sin ningun tipo de limitante.</p>
</div>
</div>
</div>
<div className="col-12 col-md-4 mt-5">
<div className="card shadow-sm">
<div className="card-body">
<h5 className="card-title font-weight-bold">Mide el peso de tus ingredientes</h5>
<p className="card-text">Al agregar un ingrediente en tu receta se podra medir el peso de cada uno de estos dependiendo de la medida que se utilizo(gr, litros, ml, etc...)).</p>
</div>
</div>
</div>
<div className="col-12 col-md-4 mt-5">
<div className="card shadow-sm">
<div className="card-body">
<h5 className="card-title font-weight-bold">Modifica y elimina tus recetas</h5>
<p className="card-text">Si tu receta cambio o simplemente ya no la necesitas podras editarla y elimnarla en cualquier momento.</p>
</div>
</div>
</div>
</div>
</div>
</>
)
}
<file_sep>/src/screens/TusRecetas/index.tsx
import axios from 'axios';
import jwt from 'jsonwebtoken'
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { toast } from 'react-toastify';
import chefsitoMirar from '../../assets/img/chef-receta-3.svg';
import { RecetaList } from '../../components/RecetaList';
import './styles/tusRecetasStyles.scss';
type Recipe = {
authorId: string,
title: string,
description: string,
categoryId: string,
ingredients: any[],
procedure: string
}
export const TusRecetas = () => {
const history = useHistory();
const [recipes, setRecipes] = useState<Recipe[]>();
const [categories, setCategories] = useState<any>();
const [hasRemoved, setHasRemoved] = useState<boolean>(false);
useEffect(() => {
const getRecipes = async () => {
try {
const token = window.localStorage.getItem('rttoken');
if (!token) {
history.push('/log-in')
return;
}
const tokenDecoded: any = jwt.decode(token);
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/recipes');
setRecipes(data.data.recipes.filter((recipe: Recipe) => recipe.authorId === tokenDecoded.id))
} catch (error) {
toast.error(error.response.data.message)
}
}
getRecipes()
return () => {
setRecipes([])
}
}, [hasRemoved]);
useEffect(() => {
const getCategories = async () => {
try {
const { data } = await axios.get('https://recetario-app-edmv.herokuapp.com/categories');
setCategories(data.data.categories)
} catch (error) {
toast.error(error.response.data.message);
}
}
getCategories()
return () => {
setCategories([])
}
}, []);
const handleDeleteRecipe = async (id:string) => {
try {
const token = window.localStorage.getItem('rttoken');
const options = {
headers: {
authorization: token
}
}
const { data } = await axios.delete(`https://recetario-app-edmv.herokuapp.com/recipes/${id}`, options);
setHasRemoved(true);
setHasRemoved(false);
} catch (error) {
toast.error(error.response.data.message)
}
}
return (
<div className="container container-fluid">
<div className="row pb-5">
<div className="col-12 col-md-5 d-flex flex-column justify-content-center text-header-wrapper">
<h1>Tus recetas</h1>
<p>En esta seccion podras encontrar todas las recetas que haz agregado.</p>
</div>
<div className="col-12 col-md-7 mt-4">
<div className="img-header-wrapper">
<img src={chefsitoMirar} alt="chefsito" className="w-50" />
</div>
</div>
</div>
<div className="row">
<div className="col-12 text-white">
<div className="w-100 bg-primary-color p-2 px-3 rounded">
<div className="w-100 d-flex justify-content-between align-items-center">
<h4>Tus recetas</h4>
<span className="icon-sm text-white fas fa-plus-circle pointer" onClick={()=>history.push('/crear-recetas')}></span>
</div>
</div>
<div className="w-100 list-group text-dark mt-3">
{
!recipes || !categories ?
null
:
recipes.map((recipe: any) => <RecetaList key={recipe._id} recipe={recipe} categories={categories} handleDeleteRecipe={handleDeleteRecipe} />)
}
</div>
</div>
</div>
</div>
)
}
|
ad91510ca9a6c2c383fda4a8c4f06abcadf7e24c
|
[
"TSX"
] | 14 |
TSX
|
DemianMtz1/recetari.o-client
|
8abb9827362db87c1d6ddbfb7830b8f7da9f9432
|
20204909f3b9a4261c81a61817f98d7c87214773
|
refs/heads/master
|
<repo_name>caotrimai/fitmeal-ui<file_sep>/src/common/service/orderService.js
import { orderData } from './order-data'
export const fetchAll = async () => {
return JSON.parse(JSON.stringify(orderData))
}
export const fetch = async (userId, week) => {
}
export const save = async (orders) => {
const newOrders = orderData.concat([orders]);
// write data to output stream...
return { data: newOrders };
}<file_sep>/src/components/styles/WeekCombo.scss
.week-combo {
width: 100%;
background-color: #fff;
padding: 10px 10px 5px 10px;
&__title {
color: #c3332a;
font-weight: bold;
font-size: 14px;
text-transform: uppercase;
border-bottom: 1px solid #5b5b5b;
padding: 0px 10px 0px 10px;
}
&__col {
padding: 5px 10px 5px 10px;
}
.ant-cart-body {
padding: 10px 15px 0px 15px;
width: 258px;
height: 127px;
}
}
<file_sep>/src/app/reducers/userSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { register, login } from '../thunks/userThunk'
import userService from "common/service/userService";
let users = userService.fetchAll();
const initialState = {
users,
register: null,
registerError: null
};
const userSlice = createSlice({
name: "user",
slice: "userSlice",
initialState: initialState,
reducers: {
add(state, action) {
state.users = state.users ? state.users.concat(action.payload) : [action.payload];
}
},
extraReducers: {
[register.pending]: (state, action) => { state.register = 'pending' },
[register.fulfilled]: (state, action) => {
state.currentUser = action.payload;
state.register = 'done';
state.users = userService.fetchAll();
// set another states
},
[register.rejected]: (state, action) => { state.registerError = action.payload },
[login.fulfilled]: (state, action) => {
state.users = userService.fetchAll();
// set another states
},
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = userSlice;
// Extract and export each action creator by name
export const { add } = actions;
// Export the reducer, either as a default or named export
export default reducer;
<file_sep>/src/features/login/components/styles/FormSeparator.scss
.form-separator {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding: 1rem;
.dash {
width: 140px;
border: 0.03125rem solid #dbdbdb;
}
.content {
color: #ccc;
padding: 0 1rem;
text-transform: uppercase;
}
}
<file_sep>/src/app/thunks/userThunk.js
import { createAsyncThunk } from "@reduxjs/toolkit";
import { setVisibleRegForm } from "features/register/reducer/registerSlice";
import userService from "common/service/userService";
export const register = createAsyncThunk(
'user/register',
async (user, thunkAPI) => {
try {
return new Promise((resolve, reject) => {
setTimeout(() => {
const response = userService.register(user);
resolve(response.data);
}, 500);
thunkAPI.dispatch(setVisibleRegForm(false));
});
} catch (error) {
console.log(error);
throw error;
}
}
);
export const login = createAsyncThunk(
'user/login',
async (user, thunkAPI) => {
try {
const response = await userService.login(user.phone, user.password);
return response.data;
} catch (error) {
console.log(error);
throw error;
}
}
);<file_sep>/src/app/reducers/foodComboSlice.js
import { createSlice } from "@reduxjs/toolkit";
import { fetchAllFoodCombos } from '../thunks/productThunk'
const initialState = {
foodCombos: [],
loading: false,
error: ''
};
const foodComboSlice = createSlice({
name: "foodCombo",
slice: "foodComboSlice",
initialState: initialState,
reducers: {
},
extraReducers: {
[fetchAllFoodCombos.pending]: (state, action) => {
state.loading = true
},
[fetchAllFoodCombos.fulfilled]: (state, action) => {
state.loading = false;
state.foodCombos = action.payload;
},
[fetchAllFoodCombos.rejected]: (state, action) => {
state.loading = false;
state.error = action.error;
}
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = foodComboSlice;
// Extract and export each action creator by name
export const { add } = actions;
// Export the reducer, either as a default or named export
export default reducer;
<file_sep>/src/app/reducers/authenticationSlice.js
import { createSlice } from "@reduxjs/toolkit";
import { register, login } from '../thunks/userThunk'
const initialState = {
loggedIn: false,
currentUser: null,
};
const authenticationSlice = createSlice({
name: "authentication",
slice: "authenticationSlice",
initialState: initialState,
reducers: {
},
extraReducers: {
[login.fulfilled]: (state, action) => {
state.currentUser = action.payload;
state.loggedIn = true;
},
[register.fulfilled]: (state, action) => {
state.currentUser = action.payload;
state.loggedIn = true;
},
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = authenticationSlice;
// Extract and export each action creator by name
export const { } = actions;
// Export the reducer, either as a default or named export
export default reducer;
<file_sep>/src/features/Cart/common/CartFunction.js
import uniqid from 'uniqid';
export const addProductToCart = (productId, cartProducts, week, userId) => {
const productExists = cartProducts.find(cartItem => cartItem.productId === productId && cartItem.week === week);
const cartItemId = uniqid.process(userId + '-' + week + '-');
const newProduct = productExists ? { ...productExists, amount: productExists.amount + 1 }
: { cartItemId, productId, amount: 1, week, };
return [newProduct].concat(cartProducts.filter(cartItem => (cartItem.cartItemId !== newProduct.cartItemId)));
}<file_sep>/src/features/login/reducer/loginSlice.js
import { createSlice } from "@reduxjs/toolkit";
import { login } from 'app/thunks/userThunk'
const initialState = {
visibleLoginForm: false,
loginError: false,
}
const loginSlice = createSlice({
name: "login",
slice: "loginSlice",
initialState,
reducers: {
setVisibleLoginForm(state, action) {
state.visibleLoginForm = action.payload;
}
},
extraReducers: {
[login.fulfilled]: (state, action) => {
state.visibleLoginForm = false;
},
[login.rejected]: (state, action) => {
state.loginError = action.error.message;
},
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = loginSlice;
// Extract and export each action creator by name
export const { setVisibleLoginForm } = actions;
// Export the reducer, either as a default or named export
export default reducer;
<file_sep>/src/app/reducers/cartSlice.js
import { createSlice } from "@reduxjs/toolkit";
import _ from 'lodash';
import { fetchByCartIds } from 'common/service/productService'
import { save as saveOrder } from '../thunks/orderThunk'
const getTotalPrice = (products) => {
let totalPrice = 0;
for (const product of products) {
totalPrice += parseInt(product.price) * parseInt(product.amount);
}
return totalPrice
}
const items = localStorage.getItem('cart.items') ? JSON.parse(localStorage.getItem('cart.items')) : [];
const products = fetchByCartIds(items)
const totalPrice = getTotalPrice(products);
const initialState = {
items,
totalPrice
}
const cartSlice = createSlice({
name: "cart",
slice: "cartSlice",
initialState: initialState,
reducers: {
setProducts(state, action) {
localStorage.setItem('cart.items', JSON.stringify(action.payload));
const items = fetchByCartIds(action.payload);
const totalPrice = getTotalPrice(items);
state.items = action.payload;
state.totalPrice = totalPrice;
},
remove(state, action) {
state.items = _.remove(state.items, action.payload);
},
clear(state) {
state.items = [];
state.totalPrice = 0;
localStorage.setItem('cart.items', []);
}
},
extraReducers: {
[saveOrder.fulfilled]: (state, action) => {
state.items = [];
state.totalPrice = 0;
localStorage.setItem('cart.items', []);
}
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = cartSlice;
// Extract and export each action creator by name
export const { setProducts, remove, clear } = actions;
// Export the reducer, either as a default or named export
export default reducer;<file_sep>/src/features/login/components/LoginForm/index.js
import React from 'react';
import { Redirect } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useForm, Controller } from "react-hook-form";
import { useDispatch, useSelector } from "react-redux";
import { phoneReg } from 'common/constant/regex';
import { login } from 'app/thunks/userThunk'
import '../styles/LoginForm.scss';
import 'antd/dist/antd.css';
import { Form, Input, Button } from 'antd';
function LoginForm(props) {
const dispatch = useDispatch();
const { t } = useTranslation();
const isLoggedIn = useSelector(state => state.authen.loggedIn);
const referrer = useSelector(state => state.location.referrer);
const loginError = useSelector(state => state.login.loginError);
const { control, errors, handleSubmit, setValue } = useForm();
const phoneErrRequired = errors.phone?.type === "required" && t('This is a required field!');
const phoneErrPattern = errors.phone?.type === "pattern" && t('Please input a valid phone number!');
const phoneError = [phoneErrRequired, phoneErrPattern];
const passwordErrRequired = errors.password?.type === "required" && t('This is a required field!');
const passwordErrMinLength = errors.password?.type === "minLength" && t('Password must be minimum 6 characters.');
const passwordError = [passwordErrRequired, passwordErrMinLength];
const onSubmit = data => {
dispatch(login(data));
};
const PhoneInput = (
<Form.Item>
<Input
id="phone"
type="text"
placeholder={t('Phone number')}
onChange={e => setValue('phone', e.target.value, true)}
onBlur={e => setValue('phone', e.target.value, true)}
/>
</Form.Item>
);
const PasswordInput = (
<Form.Item>
<Input.Password
type="password"
placeholder={t('Password')}
onChange={e => setValue('password', e.target.value, true)}
onBlur={e => setValue('password', e.target.value, true)}
/>
</Form.Item>
);
if (isLoggedIn) {
return referrer ? <Redirect to={referrer} /> : <Redirect to='/' />
} else {
return (
<form
onSubmit={handleSubmit(onSubmit)}
className="login-form"
>
<Controller
as={PhoneInput}
name="phone"
control={control}
rules={{
required: true,
pattern: new RegExp(phoneReg),
}}
validateStatus={phoneError ? 'error' : ''}
help={phoneError}
/>
<Controller
as={PasswordInput}
name="password"
control={control}
rules={{
required: true,
minLength: 6
}}
validateStatus={passwordError ? 'error' : ''}
help={passwordError}
/>
{loginError && <span className="error-message">{t(loginError)}</span>}
<Button block className="next-button" type="primary" htmlType="submit">
{t('Login')}
</Button>
</form>
);
}
}
export default LoginForm;<file_sep>/src/features/common/Router/PrivateRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { Path } from 'common/constant/path'
import { useSelector, useDispatch } from 'react-redux'
import { setReferrer } from 'app/reducers/locationSlice'
function PrivateRoute({ component: Component, exact, path, strict, ...props }) {
const dispatch = useDispatch();
const isLoggedIn = useSelector(state => state.authen.loggedIn);
let currentLocation = window.location.pathname;
if (isLoggedIn) currentLocation = '/'
dispatch(setReferrer(currentLocation));
return (!isLoggedIn ?
<Redirect
to={{
pathname: Path.login
}}
/>
:
<Route {...props}
component={Component}
exact={exact}
strict={strict}
path={path}
/>
);
}
export default PrivateRoute;<file_sep>/src/common/service/product-menu-data.js
export const productMenu = [
{
id: 'pm1',
productId: '1',
date: '2020-06-22',
breakfast: 'Phở bò tái',
lunch: 'Thịt kho trứng',
dinners: 'Cơm sườn'
},
{
id: 'pm2',
productId: '1',
date: '2020-06-23',
breakfast: 'Hủ tíu nam vang',
lunch: 'Chả cá sốt cà chua',
dinners: 'Phở gà'
},
{
id: 'pm3',
productId: '1',
date: '2020-06-24',
breakfast: 'Bánh canh chả cá',
lunch: 'Canh chua cá hú',
dinners: 'Phở gà',
},
{
id: 'pm4',
productId: '1',
date: '2020-06-25',
breakfast: 'Phở bò tái',
lunch: 'Chả cá sốt cà chua',
dinners: 'Phở gà'
},
{
id: 'pm5',
productId: '1',
date: '2020-06-26',
breakfast: 'Bánh canh chả cá',
lunch: 'Canh chua cá hú',
dinners: 'Cơm sườn',
},
{
id: 'pm6',
productId: '1',
date: '2020-06-27',
breakfast: 'Bánh canh chả cá',
lunch: 'Cá kho tộ',
dinners: 'Cơm sườn'
},
{
id: 'pm7',
productId: '1',
date: '2020-06-28',
breakfast: 'Hủ tíu nam vang',
lunch: 'Canh chua cá hú',
dinners: 'Phở gà'
},
]<file_sep>/src/app/reducers/locationSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
referrer: null,
};
const locationSlice = createSlice({
name: "location",
slice: "locationSlice",
initialState: initialState,
reducers: {
setReferrer: (state, action) => {
state.referrer = action.payload
}
},
extraReducers: {
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = locationSlice;
// Extract and export each action creator by name
export const { setReferrer } = actions;
// Export the reducer, either as a default or named export
export default reducer;
<file_sep>/src/components/RelatedProducts/index.js
import React, { useEffect, useState } from 'react';
import { NavLink } from "react-router-dom";
import { useTranslation } from 'react-i18next';
import { getRelatedProducts } from 'common/service/productService'
import FoodCombo from 'components/FoodCombo';
import { Row, Col } from 'antd';
import 'antd/dist/antd.css';
import '../styles/RelatedProducts.scss';
function RelatedProducts(props) {
const { t } = useTranslation();
const [weekCombos, setWeekCombos] = useState([]);
useEffect(() => {
async function fetchWeekCombos() {
const response = await getRelatedProducts();
setWeekCombos(response.slice(0, 6));
}
fetchWeekCombos();
}, []);
const foodCombos = [];
for (const combo of weekCombos) {
foodCombos.push(
<Col span={4} key={combo.id} className="related-products__col">
<NavLink to="/p/detail">
<FoodCombo combo={combo} />
</NavLink>
</Col>
);
}
return (
<Row className="related-products">
{weekCombos &&
<Col>
<Row>
<Col span={24} className="related-products__title">
<div>{t('Related products')}</div>
</Col>
</Row>
<Row>
{foodCombos}
</Row>
</Col>
}
</Row>
);
}
export default RelatedProducts;<file_sep>/src/common/service/userService.js
import { userData } from './users-data.js'
let users = userData;
const fetchAll = () => {
return [...users];
}
export const checkPhoneIsExists = (phone) => {
return users.find((user) => user.phone === phone) ? { data: true } : { data: false };
}
const fetchByPhone = (phone) => {
return users.find((user) => user.phone === phone);
}
const fetchByPhoneAndPassword = (phone, password) => {
return users.find((user) => user.phone === phone && user.password === password);
}
const register = (user) => {
try {
const existUser = fetchByPhone(user.phone);
if (!existUser) {
users.push(user);
return { data: user };
} else {
throw new Error('This phone is already registered');
}
} catch (error) {
throw error;
}
}
const login = (phone, password) => {
try {
const existUser = fetchByPhoneAndPassword(phone, password);
if (existUser) {
return { data: existUser };
} else {
throw new Error('The username or password is incorrect!');
}
} catch (error) {
throw error;
}
}
const userService = {
fetchAll,
fetchByPhone,
register,
login
}
export default userService;<file_sep>/src/features/Cart/styles/CartInner.scss
.cart-inner {
min-width: 1010px;
width: 100%;
}
.cart-products {
padding: 10px 0px 10px 0px;
&__title {
margin-top: 50px;
padding: 10px 0px 10px 0px;
background-color: #fff;
border-radius: 1px;
border: unset;
box-shadow: 0.3px 0.3px 1px #888888;
color: #999999;
font-size: 16px;
text-align: center;
&__color-black {
color: #000;
}
&__text-left {
text-align: left;
}
}
&__products {
margin-top: 20px;
padding: 10px 0px 10px 0px;
background-color: #fff;
border-radius: 1px;
border: unset;
box-shadow: 0.3px 0.3px 1px #888888;
color: #999999;
font-size: 16px;
text-align: center;
&__img img {
width: 108px;
height: 68px;
}
&__price {
color: #c3332a;
}
&__amount {
&--width-60px {
width: 60px;
}
}
&__manipulation {
color: #000;
cursor: pointer;
}
&__text-left {
text-align: left;
}
}
&__total-prices {
margin-top: 20px;
margin-bottom: 20px;
padding: 10px 0px 10px 0px;
border-radius: 1px;
border: unset;
box-shadow: 0.3px 0.3px 1px #888888;
background-color: #fff;
color: #000;
&__text-left {
text-align: left;
}
&__color-#C3332A {
color: #c3332a;
}
&__purchase-btn button {
background-color: #ec7533;
border: unset;
}
&__purchase-btn button:hover,
&__purchase-btn button:focus {
background-color: #f5b43c;
border: unset;
}
}
}
<file_sep>/src/App.js
import React from 'react';
import RootRouter from './RootRouter';
import './App.scss';
import './common/config/i18n';
function App() {
return (
<div className="App" style={{ background: '#E5E5E5' }}>
<RootRouter />
</div>
);
}
export default App;
<file_sep>/src/features/ProductMenu/pages/ProductMenuPage/index.js
import React, { useState } from 'react'
import { filter as filterUserProductMenu } from 'common/service/userProductMenuService'
import { useTranslation } from 'react-i18next'
import { useSelector } from 'react-redux'
import moment from 'moment'
import { Row, Col, DatePicker } from 'antd';
import '../../styles/ProductMenuPage.scss'
import ProductMenuBody from '../ProductMenuBody';
function ProductMenuPage(props) {
const { t } = useTranslation();
const currentUser = useSelector(state => state.authen.currentUser);
const [weekMenu, setWeekMenu] = useState([])
const getDateFromWeek = (year, week) => {
const fromDate = moment().day("Sunday").year(year).week(week).format('YYYY-MM-DD');
const toDate = moment().day("Saturday").year(year).week(week).format('YYYY-MM-DD');
return { fromDate, toDate };
};
const onChangeTime = (date, dateString) => {
const year = dateString.substring(0, 4);
const week = dateString.substring(5, 7);
const time = getDateFromWeek(year, week);
const weekMenu = filterUserProductMenu(currentUser.id, 1, time.fromDate, time.toDate);
setWeekMenu(weekMenu);
}
return (
<div className="product-menu">
<Row className="date-input">
<div className="date-input-title">{t('Time')}</div>
<DatePicker id="datePicker" onChange={onChangeTime} picker="week" />
</Row>
<Row className="product-menu-header">
<Col className="header-name header-name__color-yellow" span={3}>{t('Date')}</Col>
<Col className="header-name header-name__border-left" span={7}>{t('Morning')}</Col>
<Col className="header-name header-name__border-left" span={7}>{t('Lunch')}</Col>
<Col className="header-name header-name__border-left" span={7}>{t('Dinner')}</Col>
</Row>
{weekMenu && <div className="product-menu-body">
<ProductMenuBody weekMenu={weekMenu} />
</div>}
</div>
);
}
export default ProductMenuPage;<file_sep>/src/components/LoadingPage/index.js
import React from 'react';
import '../styles/LoadingPage.scss';
import 'antd/dist/antd.css';
import { Spin } from 'antd';
function LoadingPage(props) {
return (
<div className="loading-page">
<Spin />
</div>
);
}
export default LoadingPage;<file_sep>/src/components/BannerHotword/index.js
import React from 'react';
import { Row, Col, Carousel } from 'antd';
import MainBanner1 from 'assets/images/banner1.jpg'
import MainBanner2 from 'assets/images/banner2.jpg'
import MainBanner3 from 'assets/images/banner3.jpg'
import RightBanner1 from 'assets/images/right-banner1.png'
import RightBanner2 from 'assets/images/right-banner2.png'
import 'antd/dist/antd.css';
import '../styles/SectionBannerHotword.scss';
function SectionBannerHotword(props) {
return (
<div className="banner-hotword">
<Row>
<Col span={18} className="banner-hotword__left">
<Carousel autoplay>
<div>
<img src={MainBanner1} className="banner-hotword__left__img" alt="RedexpressBanner" />
</div>
<div>
<img src={MainBanner2} className="banner-hotword__left__img" alt="RedexpressBanner" />
</div>
<div>
<img src={MainBanner3} className="banner-hotword__left__img" alt="RedexpressBanner" />
</div>
</Carousel>
</Col>
<Col span={6} className="banner-hotword__right">
<Row><img src={RightBanner1} className="banner-hotword__right__img banner-hotword__right--padding-top" alt="RedexpressBanner" /></Row>
<Row><img src={RightBanner2} className="banner-hotword__right__img banner-hotword__right--padding-bottom" alt="RedexpressBanner" /></Row>
</Col>
</Row>
</div>
);
}
export default SectionBannerHotword;<file_sep>/src/features/Cart/components/CartProduct/index.js
import React from 'react';
import { useTranslation } from 'react-i18next';
import PropTypes from 'prop-types';
import { Row, Col, Button, InputNumber } from 'antd';
import 'features/Cart/styles/CartInner.scss'
CartProduct.propTypes = {
};
function CartProduct(props) {
const { product } = props;
return (
<Row className='cart-products__products'>
<Col span={1}></Col>
<Col span={2} className='cart-products__products__img'> <img src={product.img} /> </Col>
<Col span={13}
className='cart-products__products__content
cart-products__products__text-left'
> {product.name}</Col>
<Col span={2} className='cart-products__products__unit-price'> {product.price}</Col>
<Col span={2} className='cart-products__products__amount'> <InputNumber min={1} max={10} defaultValue={1} onChange={} /></Col>
<Col span={2} className='cart-products__products__price'> 600.000đ</Col>
<Col span={2} className='cart-products__products__manipulation'> Xóa</Col>
</Row>
);
}
export default CartProduct;<file_sep>/src/components/styles/Header.scss
.register-modal {
.ant-modal-body {
padding: 10px 10px 10px 10px;
}
}
.login-modal {
.ant-modal-body {
padding: 10px 10px 10px 10px;
}
}
<file_sep>/src/features/login/components/FormSeparator/index.js
import React from 'react';
import PropTypes from 'prop-types';
import '../styles/FormSeparator.scss'
FormSeparator.propTypes = {
content: PropTypes.string,
};
function FormSeparator(props) {
const { content } = props
return (
<div className="form-separator">
<div className="dash"></div>
<div className="content">{content}</div>
<div className="dash"></div>
</div>
);
}
export default FormSeparator;<file_sep>/src/features/ProductMenu/pages/ProductMenuBody/index.js
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { useTranslation } from 'react-i18next';
import { Row, Col } from 'antd';
import '../../styles/ProductMenuBody.scss'
ProductMenuBody.propTypes = {
weekMenu: PropTypes.arrayOf(PropTypes.shape({
date: PropTypes.date,
breakfast: PropTypes.string,
lunch: PropTypes.string,
dinners: PropTypes.string
}))
};
function ProductMenuBody(props) {
const { t } = useTranslation();
const { weekMenu } = props;
var menuSchedule = [];
for (let i = 0; i < weekMenu.length; i++) {
const date = moment(weekMenu[i].date, 'YYYY-MM-DD');
const weekDayName = `${date.format('dddd')}`;
const dateMonth = `${date.get('date')}-${date.get('month') + 1}`;
menuSchedule.push(
<Row className="day-menu" key={weekMenu[i].id}>
<Col className="menu-date" span={3}> <div className="menu-date__wrapper">{t(weekDayName)} <br /> {dateMonth}</div> </Col>
<Col className="menu-food" span={7}>{weekMenu[i].breakfast}</Col>
<Col className="menu-food" span={7}>{weekMenu[i].lunch}</Col>
<Col className="menu-food" span={7}>{weekMenu[i].dinners}</Col>
</Row>
)
}
return menuSchedule
}
export default ProductMenuBody;<file_sep>/src/features/Product/components/Model/Product.js
export default function Product(id, name, type, restaurant, introduce, description, price) {
this.id = id;
this.name = name;
this.type = type;
this.restaurant = restaurant;
this.introduce = introduce;
this.description = description;
this.price = price;
}<file_sep>/src/features/Product/components/ProductDetail/index.js
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { Row, Col, Carousel, Button, DatePicker, Alert, Modal } from 'antd';
import { setProducts } from 'app/reducers/cartSlice'
import 'antd/dist/antd.css';
import 'features/Product/styles/ProductDetail.scss';
import { addProductToCart } from 'features/Cart/common/CartFunction'
import Picture1 from 'assets/images/product-detail/p-detail1.jpg'
import Picture2 from 'assets/images/product-detail/p-detail2.jpg'
import { useDispatch } from 'react-redux';
ProductDetail.propTypes = {
product: PropTypes.shape({
id: PropTypes.number,
name: PropTypes.string,
type: PropTypes.string,
restaurant: PropTypes.string,
introduce: PropTypes.string,
description: PropTypes.string,
price: PropTypes.number
}).isRequired
};
function ProductDetail(props) {
const { product } = props;
const dispatch = useDispatch();
const cartItems = useSelector(state => state.cart.items);
const currentUser = useSelector(state => state.authen.currentUser);
const [visibleErrorModal, setVisibleErrorModal] = useState(false);
const [modalErrMessage, setModalErrMessage] = useState('');
const { t } = useTranslation();
let weekSelected = null;
function onWeekChange(date, dateString) {
weekSelected = dateString
}
const addToCart = () => {
weekSelected = document.getElementById("datePicker").value;
if (!currentUser) {
setModalErrMessage('Please login first');
showModal();
} else if (weekSelected) {
// const newProducts = addProductToCart(product.id, cartItems, weekSelected, currentUser.id);
const newProducts = { productId: product.id, weekSelected, userId: currentUser.id };
dispatch(addToCart(newProducts));
} else {
setModalErrMessage('Please select week')
showModal();
}
}
const showModal = () => {
setVisibleErrorModal(true)
};
const handleOk = e => {
setVisibleErrorModal(false)
};
const handleCancel = e => {
setVisibleErrorModal(false)
};
return (
<Row className="product-detail">
<Col span={8} className="product-detail-left">
<Carousel autoplay>
<div>
<img src={Picture1} className="product-detail-left__img" alt="RedexpressBanner" />
</div>
<div>
<img src={Picture2} className="product-detail-left__img" alt="RedexpressBanner" />
</div>
</Carousel>
</Col>
<Col span={16} className="product-detail-right">
<div className="product-detail-right__name">{product.name}</div>
<div className="product-detail-right__price">{product.price}đ</div>
<DatePicker id="datePicker" onChange={onWeekChange} picker="week" />
<div className="add-to-cart">
<Button
htmlType="submit"
onClick={addToCart}
className="add-to-cart__btn"
type="primary"
>
{t('Add to cart')}
</Button>
</div>
<div className="product-detail-right__description">
{product.description}
</div>
</Col>
<Modal
className="error-modal"
width='fit-content'
closable={false}
header={null}
visible={visibleErrorModal}
onOk={handleOk}
onCancel={handleCancel}
>
< Alert
message="Error"
description={modalErrMessage}
type="error"
showIcon
/>
</Modal>
</Row>
);
}
export default ProductDetail;<file_sep>/src/features/Product/styles/SellerBanner.scss
.seller-banner {
background-color: #fff;
width: 100%;
&-left {
&__img {
width: 106px;
height: 106px;
}
}
&-right {
&__name {
}
&__rating {
color: #ec7533;
}
&__btn-group {
width: 250px;
padding: 5px 0px 5px 0px;
display: flex;
flex-direction: row;
justify-content: space-between;
&__btn {
width: 120px;
background-color: #ec7533;
border-color: #ec7533;
text-align: center;
}
&__btn:hover,
&__btn:focus {
background-color: #f5b43c;
border-color: #f5b43c;
}
}
}
}
<file_sep>/src/common/config/configureStore.js
import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'
import { reduxBatch } from '@manaflair/redux-batch';
// import logger from 'redux-logger'
import rootReducer from '../../features/rootReducer.js'
const middleware = [
...getDefaultMiddleware(),
// logger
]
const store = configureStore({
reducer: rootReducer,
middleware,
devTools: process.env.NODE_ENV !== 'production',
enhancers: [reduxBatch]
})
export default store
// The store has been created with these options:
// - The slice reducers were automatically passed to combineReducers()
// - redux-thunk and redux-logger were added as middleware
// - The Redux DevTools Extension is disabled for production
// - The middleware, batch, and devtools enhancers were automatically composed together<file_sep>/src/features/HomePage/pages/index.js
import { Row } from 'antd';
import SectionBannerHotword from 'components/BannerHotword';
import WeekCombo from 'components/WeekCombo';
import React from 'react';
import '../styles/HomePage.scss';
function HomePage(props) {
return (
<div className="home-page">
<div className="main-content">
<Row className="main-content__row"><SectionBannerHotword /></Row>
<Row className="main-content__row"><WeekCombo /></Row>
{/* <Row className="main-content__row"><WeekCombo /></Row> */}
</div>
</div>
);
}
export default HomePage;<file_sep>/src/features/ProductMenu/styles/ProductMenuPage.scss
.product-menu {
padding: 10px 10px 10px 10px;
}
.product-menu-header {
background-color: #39393b;
padding: 10px 0px 10px 0px;
color: #fff;
font-weight: bold;
text-align: center;
text-transform: uppercase;
.header-name {
&__color-yellow {
color: #ec7533;
}
&__border-left {
border-left: 1px solid #fff;
}
}
}
<file_sep>/src/components/styles/SectionBannerHotword.scss
.banner-hotword {
padding: 10px 0px 10px 5px;
background-color: #fff;
min-width: 1140px;
&__right {
padding: 0px 5px 0px 5px;
&__img {
height: 140px;
width: 100%;
}
&--padding-bottom {
padding: 0px 0px 3px 0px;
}
&--padding-top {
padding: 3px 0px 0px 0px;
}
}
&__left {
&__img {
height: 280px;
width: 100%;
}
}
}
<file_sep>/src/components/styles/LoginBtnCombo.scss
@mixin btn-wrapper($width, $height) {
width: $width;
height: $height;
}
@mixin single-btn() {
width: 100%;
.btn-icon {
margin-left: -10px;
float: left;
font-size: 22px;
}
}
.login-btn-combo {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
.facebook-btn-wrapper {
@include btn-wrapper(215px, 40px);
padding: 0px 5px 0px 0px;
.single-btn {
@include single-btn();
}
}
.google-btn-wrapper {
@include btn-wrapper(215px, 40px);
padding: 0px 0px 0px 5px;
.single-btn {
@include single-btn();
}
}
}
<file_sep>/src/features/Cart/index.js
import React from 'react';
import { Route, Switch, useRouteMatch } from 'react-router-dom';
import NotFound from 'components/NotFound';
import CartPage from './pages/CartPage';
Cart.propTypes = {};
function Cart(props) {
const match = useRouteMatch();
return (
<Switch>
<Route exact path={`${match.url}`}
render={({ match }) => <CartPage match={match} />} />
<Route component={NotFound} />
</Switch>
);
}
export default Cart;<file_sep>/src/app/reducers/languageSlice.js
import { createSlice } from "@reduxjs/toolkit";
const languageSlice = createSlice({
name: "language",
slice: "languageSlice",
initialState: "vi_VN",
reducers: {
changeLanguage(state, action) {
state.language = action.payload;
},
resetDefaultLanguage(state, action) {
state.language = "en_US";
}
}
});
// console.log(languageSlice);
// Extract the action creators object and the reducer
const { actions, reducer } = languageSlice;
// Extract and export each action creator by name
export const { changeLanguage, resetDefaultLanguage } = actions;
// Export the reducer, either as a default or named export
export default reducer;
<file_sep>/src/features/Product/components/SellerBanner/index.js
import React from 'react';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
import { Row, Col, Button } from 'antd';
import 'antd/dist/antd.css';
import 'features/Product/styles/SellerBanner.scss';
import logo from 'assets/images/good-food-logo.png';
SellerBanner.propTypes = {
};
function SellerBanner(props) {
const { t } = useTranslation();
return (
<Row className="seller-banner ">
<Col span={4} className="seller-banner-left">
<img src={logo} className="seller-banner-left__img" alt="RedexpressBanner" />
</Col>
<Col span={20} className="seller-banner-right">
<div className="seller-banner-right__name">FITFOOD.VN</div>
<div className="seller-banner-right__rating">{t('Rating')} 4.3 <i className="zmdi zmdi-star"></i></div>
<div className="seller-banner-right__btn-group">
<Button className="seller-banner-right__btn-group__btn" type="primary">{t('Chat now')}</Button>
<Button className="seller-banner-right__btn-group__btn" type="primary">{t('View restaurant')}</Button>
</div>
</Col>
</Row>
);
}
export default SellerBanner;<file_sep>/src/features/register/reducer/registerSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
visibleRegForm: false,
}
const registerSlice = createSlice({
name: "register",
slice: "registerSlice",
initialState,
reducers: {
setVisibleRegForm(state, action) {
state.visibleRegForm = action.payload;
}
},
extraReducers: {
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = registerSlice;
// Extract and export each action creator by name
export const { setVisibleRegForm } = actions;
// Export the reducer, either as a default or named export
export default reducer;
<file_sep>/src/common/constant/currencyFormater.js
import currencyFormatter from 'currency-formatter';
export const vndFormatter = (amount) => {
return currencyFormatter.format(amount, { code: 'VND' })
}<file_sep>/src/components/FoodCombo/index.js
import React from 'react';
import PropTypes from 'prop-types';
import { Card } from 'antd';
import 'antd/dist/antd.css';
import '../styles/FoodCombo.scss';
import Product from 'assets/images/combo-fit1.jpg'
FoodCombo.propTypes = {
combo: PropTypes.shape({
name: PropTypes.string,
price: PropTypes.number,
introduce: PropTypes.string
}).isRequired
};
// function ProductCart(props) {
function FoodCombo(props) {
const { combo } = props;
return (
<Card
className="product-cart"
hoverable
cover={<img alt="Foot_picture" src={Product} />}
>
<div className="restaurant-combo__name">{combo.name}</div>
<div className="restaurant-combo__price">{combo.price}</div>
<div className="restaurant-combo__description">{combo.introduce}</div>
</Card>
);
}
export default FoodCombo;<file_sep>/README.md
Fit Meal App
Setup environment
Github project: https://github.com/caotrimai/fit-meal.git
0. Strat project
```
yarn //to build yarn
yarn start //start project
```
1. Setup ReactJS app.
https://create-react-app.dev/docs/getting-started/
2. Add SCSS support
```
npm i --save-dev node-sass
```
3. Add react router
```
npm i --save react-router-dom
```
4. Add UI lib
```
npm install antd
```
5. Structure folder
```
src
|__ assets
| |__ images
| |__ fonts
| |__ styles (global styles)
|
|
|__ common
| |__ APIs
| |__ constant
| |__ config
| |__ configureStore.js
| |__ i18n.js
|
|
|__ components (shared components)
| |__ rootReducer.js
| |
| |__ Header
| |__ Footer
| |__ NotFound
| |__ Style
|
|__ features
| |__ common
| | |__ SliceReducers
| | |__ thunks
| |
| |__ Login
| |__ Components
| |__ reducer
| |__ styles
| |__ pages
| |__ index.js
|
|__ public
| |__ locales
| |__ translation
|
|__ App.js
|__ index.js
|__ RootRouter.js
```
5. Structure routing
- Use lazy load components.
- Load by features.
```
// App.js
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/photos" component={Photo} />
<Route path="/user" component={User} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
)
}
```
5. react-i18next
- create i18n.js to start configuring react-i18next.
- import i18n.js into root component.
- in sub-components, use react-i18next:
+ const { t } = useTranslation();
+ {t('The words')}
<file_sep>/src/features/Product/pages/ProductDetailPage.js
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import ProductDetail from '../components/ProductDetail';
import SellerBanner from '../components/SellerBanner';
import WeekCombo from 'components/WeekCombo';
import { productService } from 'common/service/productService'
import { Row } from 'antd';
import 'antd/dist/antd.css';
import 'features/Product/styles/ProductDetailPage.scss';
function ProductDetailPage(props) {
const { id } = useParams();
const [product, setProduct] = useState({});
useEffect(() => {
productService.fetchById(parseInt(id)).then(result => setProduct(result), error => error.message);
}, [id]);
return (
<div className="product-detail-page">
<div className="main-content">
<Row className="main-content__row"><ProductDetail product={product} /></Row>
<Row className="main-content__row"><SellerBanner /></Row>
<Row className="main-content__row"><WeekCombo /></Row>
</div>
</div>
);
}
export default ProductDetailPage;<file_sep>/src/features/HomePage/styles/HomePage.scss
.home-page {
.main-content {
min-width: 1140px;
&__row {
padding: 5px 0px 5px 0px;
}
}
}
<file_sep>/src/features/login/components/styles/LoginForm.scss
.login-form {
width: 100%;
.error-message {
color: #ff4d4f;
padding: 0px 0px 5px 0px;
}
}
.next-button {
border: none !important;
background-color: #ec7533 !important;
text-transform: uppercase !important;
&:hover {
background-color: #f5b43c !important;
}
}
<file_sep>/src/common/service/productService.js
import axiosClient from './axiosClient'
import { productData } from './products-data'
const WEEK_COMBO = 'WEEK_COMBO';
export const getRelatedProducts = () => {
return productData.filter(product => product.type === WEEK_COMBO);
}
export const fetchByParam = (param) => {
return productData.filter(product => product.name === param || product.type === param || product.restaurant === param);
}
export const fetchById = (id) => {
return productData.find(product => product.id === id);
}
export const fetchByCartIds = (items) => {
if (items)
return items.map(item => { return { ...fetchById(item.productId), ...item } });
return []
}
export const productService = {
fetchAllDailyMenu: () => {
const url = 'http://localhost:8200/d-menu/all'
return axiosClient.get(url)
},
fetchAllFoodMenu: () => {
const url = 'http://localhost:8200/w-menu/all'
return axiosClient.get(url)
},
fetchById: (id) => {
const url = `http://localhost:8200/w-menu/fetch-combo/${id}`
return axiosClient.get(url)
},
fetchRestaurantById: (id) => {
const url = `http://localhost:8200/restaurant/fetch-by-id/${id}`
return axiosClient.get(url)
},
addToCart: (id) => {
const url = `http://localhost:8200/restaurant/fetch-by-id/${id}`
return axiosClient.get(url)
},
}<file_sep>/src/common/service/productMenuService.js
import moment from 'moment'
import { productMenu } from './product-menu-data'
export const filter = (productId, startDate, endDate) => {
const result = productMenu.filter(menu => {
const isInTime = moment(menu.date, 'YYYY-MM-DD')
.isBetween(moment(startDate, 'YYYY-MM-DD').diff(1, 'days'), moment(endDate, 'YYYY-MM-DD').add(1, 'days'))
return parseInt(menu.productId) === parseInt(productId) && isInTime
});
return result.sort((currently, next) => {
return currently.date - next.date
})
}
<file_sep>/src/common/constant/regex.js
const phoneReg = /^[(]{0,1}[0-1]{1}[0-9]{2}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/;
// The following REGEX will validate any of these formats:
// (123)456-7890
// 123-456-7890
// 123.456.7890
// 1234567890
export { phoneReg };<file_sep>/src/features/login/pages/index.js
import React, { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import Header from '../components/LoginHeader'
import LoginForm from '../components/LoginForm';
import FormSeparator from '../components/FormSeparator';
import LoginBtnCombo from 'components/LoginBtnCombo';
import '../styles/login.scss';
function Login(props) {
const ref = useRef();
const { t } = useTranslation();
return (
<div id="login" className="login" ref={ref}>
<Header />
<div className="main-content">
<LoginForm />
<br />
<FormSeparator content={t('or')} />
<LoginBtnCombo />
</div>
</div>
);
}
export default Login;<file_sep>/src/features/login/components/styles/LoginHeader.scss
.login-header {
display: block;
padding: 0px 0px 30px 0px;
.left {
float: left;
font-size: 16px;
}
.right {
float: right;
font-size: 14px;
.login {
color: #c3332a;
}
}
}
<file_sep>/src/app/reducers/orderSlice.js
import { createSlice } from "@reduxjs/toolkit";
import { save } from '../thunks/orderThunk'
const initialState = {
addStt: null,
addError: null,
orders: []
};
const orderSlice = createSlice({
name: "order",
slice: "orderSlice",
initialState: initialState,
reducers: {
},
extraReducers: {
[save.pending]: (state, action) => { state.addStt = 'pending' },
[save.fulfilled]: (state, action) => {
state.addStt = 'done';
state.orders = action.payload.concat(state.payload);
},
[save.rejected]: (state, action) => { state.addError = action.payload }
}
});
// Extract the action creators object and the reducer
const { actions, reducer } = orderSlice;
// Extract and export each action creator by name
export const { } = actions;
// Export the reducer, either as a default or named export
export default reducer;<file_sep>/src/features/Cart/styles/CartPage.scss
.cart-page {
min-height: 770px;
}
<file_sep>/src/features/Cart/pages/CartPage.js
import React from 'react';
import { Row, Col } from 'antd';
import 'antd/dist/antd.css';
import 'features/Cart/styles/CartPage.scss';
import CartInner from '../components/CartInner';
function CartPage(props) {
return (
<div className='cart-page'>
<Row>
<CartInner />
</Row>
</div>
);
}
export default CartPage;<file_sep>/src/features/Cart/components/CartInner/index.js
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSelector, useDispatch } from 'react-redux';
import { vndFormatter } from 'common/constant/currencyFormater';
import { fetchByCartIds } from 'common/service/productService'
import { save as saveOrder } from 'app/thunks/orderThunk'
import CartProduct from './CartProduct'
import 'features/Cart/styles/CartInner.scss'
import { Row, Col, Button, Modal, Alert } from 'antd';
function CartInner(props) {
const dispatch = useDispatch();
const { t } = useTranslation();
const cartItems = useSelector(state => state.cart.items);
const currentUser = useSelector(state => state.authen.currentUser);
const cartProducts = fetchByCartIds(cartItems);
const totalPrice = useSelector(state => state.cart.totalPrice);
const [isShowConfirmPurchases, setShowConfirmPurchases] = useState(false);
const [modalErrMessage, setModalErrMessage] = useState('');
const [visibleErrorModal, setVisibleErrorModal] = useState(false);
const showConfirmPurchases = () => {
if (!currentUser) {
setModalErrMessage('Please login first');
showErrorModal();
} else {
setShowConfirmPurchases(true);
}
}
const handleConfirmPurchasesOk = e => {
const order = { cartOdered: cartItems, totalPrice, userId: currentUser.id };
dispatch(saveOrder(order))
setShowConfirmPurchases(false);
}
const handleConfirmPurchasesCancel = e => {
setShowConfirmPurchases(false);
}
const showErrorModal = () => {
setVisibleErrorModal(true)
}
const handleErrorOk = e => {
setVisibleErrorModal(false)
};
const handleErrorCancel = e => {
setVisibleErrorModal(false)
};
return (
<div className='cart-inner'>
<Col>
<Row className='cart-products__title'>
<Col span={1}></Col>
<Col span={15}
className='cart-products__title__color-black
cart-products__title__text-left'
>{t('Product')}</Col>
<Col span={2}>{t('Unit price')}</Col>
<Col span={2}>{t('Amount')}</Col>
<Col span={2}>{t('Price')}</Col>
<Col span={2}>{t('Manipulation')}</Col>
</Row>
{cartProducts.map(product => <CartProduct product={product} cartItems={cartItems} key={product.cartItemId} />)}
<Row className='cart-products__total-prices'>
<Col span={1}></Col>
<Col span={17} className='cart-products__total-prices__text-left'> {t('Select all')}</Col>
<Col span={2} > {t('Total money')}</Col>
<Col span={2} className='cart-products__total-prices__color-#C3332A'> {vndFormatter(totalPrice)}</Col>
<Col span={2} className='cart-products__total-prices__purchase-btn'> <Button type="primary" onClick={showConfirmPurchases}>{t('Purchase')}</Button></Col>
<Modal
title={t('Purchase confirm')}
visible={isShowConfirmPurchases}
onOk={handleConfirmPurchasesOk}
onCancel={handleConfirmPurchasesCancel}
>
<p>{t('Purchase confirm')}</p>
</Modal>
<Modal
className="error-modal"
width='fit-content'
closable={false}
header={null}
visible={visibleErrorModal}
onOk={handleErrorOk}
onCancel={handleErrorCancel}
>
< Alert
message="Error"
description={modalErrMessage}
type="error"
showIcon
/>
</Modal>
</Row>
</Col>
</div>
);
}
export default CartInner;<file_sep>/src/features/login/pages/LoginPage.js
import React from 'react';
import '../styles/LoginPage.scss'
import Login from '.';
function LoginPage(props) {
return (
<div className="login-page">
<div className="main-content">
<div className="left-content">
</div>
<div className="right-content">
<div className="login-wrapper">
<Login />
</div>
</div>
</div>
</div>
);
}
export default LoginPage;<file_sep>/src/common/config/i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import translationVI from 'public/locales/translation/vi_VN.json';
import translationUS from 'public/locales/translation/en_US.json';
// the translations
const resources = {
vi_VN: {
translation: translationVI
},
en_US: {
translation: translationUS
},
};
i18n
.use(initReactI18next)
.init({
resources,
lng: "en_US",
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;<file_sep>/src/features/Product/styles/ProductDetailPage.scss
.product-detail-page {
min-width: 1065px;
}
.main-content {
&__row {
padding: 5px 0px 5px 0px;
width: 100%;
}
}
|
3b53377f1a220ad9420c45e9224c35c02200b38d
|
[
"Markdown",
"SCSS",
"JavaScript"
] | 55 |
Markdown
|
caotrimai/fitmeal-ui
|
c2ca6e3211ccabaaa287d724fe77c20a3c93d325
|
7e5d74cea485e393cf7d921e10e3acb6435b53d3
|
refs/heads/master
|
<repo_name>jairock282/6bitProcessor<file_sep>/README.md
# 6-bit Processor
|
ae52d7f34a690e3a7b46e892fe08c1f96838c989
|
[
"Markdown"
] | 1 |
Markdown
|
jairock282/6bitProcessor
|
4ca088591c5474ee4ae14d53c7043f082364dd2e
|
b68e9e34937e2da002738abfbe85a3128b53c7ac
|
refs/heads/master
|
<repo_name>Chamindasl/kafka-cluster<file_sep>/README.md
# Kafka Multi Node Cluster on Ubuntu Focal64
## Objective
Setup a full blown multi node kafka cluster on Ubuntu Focal64 (20.04 LTS) in one click. Should be worked on Linux, Mac and Windows.
## Prerequisites
* Vagrant
* VirtualBox (or similar) as VM provider
* Ansible (Linux/Mac) or guest_ansible vagrant plugin (Widows)
* Its 6GB * 3 = 18 GB is recommended. 2GB * 3 would be enough in most cases.
## Setup
### Checkout or download the code
```
git clone https://github.com/Chamindasl/kafka-cluster.git
cd kafka-cluster
```
### Spin up the cluster
```
vagrant up
```
### Login to nodes
Password login is enabled on all 3 servers, or vagrant ssh
```
ssh vagrant@zoo1
#pwd is <PASSWORD>
or
vargant ssh zoo1
```
### Verify
```
vagrant@zoo1:~$ systemctl status confluent*
● confluent-zookeeper.service - Apache Kafka - ZooKeeper
Loaded: loaded (/lib/systemd/system/confluent-zookeeper.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2021-03-05 17:21:14 UTC; 7h ago
Docs: http://docs.confluent.io/
Main PID: 616 (java)
Tasks: 49 (limit: 6951)
Memory: 122.5M
CGroup: /system.slice/confluent-zookeeper.service
└─616 java -Xmx512M -Xms512M -server -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:+ExplicitGCInvokesConcurrent -XX:MaxInlineLevel=>
Warning: some journal files were not opened due to insufficient permissions.
● confluent-kafka.service - Apache Kafka - broker
Loaded: loaded (/lib/systemd/system/confluent-kafka.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2021-03-05 17:21:14 UTC; 7h ago
Docs: http://docs.confluent.io/
Main PID: 615 (java)
Tasks: 71 (limit: 6951)
Memory: 384.6M
CGroup: /system.slice/confluent-kafka.service
└─615 java -Xmx1G -Xms1G -server -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:+ExplicitGCInvokesConcurrent -XX:MaxInlineLevel=15 ->
vagrant@zoo1:~$ kafka-topics --list --bootstrap-server zoo1:9092
```
## Configuration
Consider following configurations in Vagrantfile
### Change Image, VM Name or number of VMs
```
IMAGE_NAME = "ubuntu/focal64"
VM_NAME = "zoo"
N = 3
```
### CPU, Memory modifications
```
config.vm.provider "virtualbox" do |v|
v.memory = 6024
v.cpus = 2
end
```
## Troubleshooting
Restart the zookeeper and kafka
```
sudo systemctl restart confluent-zookeeper confluent-kafka
```<file_sep>/Vagrantfile
IMAGE_NAME = "ubuntu/focal64"
VM_NAME = "zoo"
N = 3
Vagrant.configure("2") do |config|
config.ssh.insert_key = false
provisioner = Vagrant::Util::Platform.windows? ? :ansible_local : :ansible
config.vm.provider "virtualbox" do |v|
v.memory = 6024
v.cpus = 2
end
(1..N).each do |i|
config.vm.define "#{VM_NAME}#{i}" do |node|
node.vm.box = IMAGE_NAME
node.vm.network "private_network", ip: "192.168.50.#{i * 10}"
node.vm.hostname = "#{VM_NAME}#{i}"
node.vm.provision provisioner do |ansible|
ansible.playbook = "setup/zk-playbook.yaml"
ansible.extra_vars = {
node_ip: "192.168.50.#{i * 10}",
node_id: "#{i}",
ansible_python_interpreter:"/usr/bin/python3",
nodes: N,
VM_NAME: "#{VM_NAME}"
}
end
end
end
end
|
40193bd1468491151e8c03bb100ecd80c75d0b4c
|
[
"Markdown",
"Ruby"
] | 2 |
Markdown
|
Chamindasl/kafka-cluster
|
9befa39088920f1e5bdf1f3ddaced6021b4ff342
|
137f7debd1af204a9050cb225f8f8fc1a1e46e61
|
refs/heads/master
|
<file_sep>pshow_innovation
================
|
96e03995ecfb97b9c4b1be25259961e20461059b
|
[
"Markdown"
] | 1 |
Markdown
|
topcatv/pshow_innovation
|
1c182417d26cc733557188c3ff93c7b2417f53ce
|
ed54a2d740b2ea48da43dae3be37f9d43a59285a
|
refs/heads/master
|
<file_sep>;(function() {
new Speed().init().changeSpeed(8)
function Speed() {
var ifrDoc
var _this = this
this.init = function () {
return this.bindPlayer().rederFixedBar()
}
// 找到视频播放器所在的 document
this.bindPlayer = function () {
ifrDoc = document.querySelector('iframe#iframe').contentWindow.document.querySelector('iframe').contentWindow.document
return this
}
// 渲染悬浮小工具
this.rederFixedBar = function () {
var fixedBar = document.createElement('div')
fixedBar.innerHTML = `
<div class="fixed-container">
<input class="rate-input" type="number" value="8"/>
<a class="rate-change a-btn" href="#balabala">设置倍率</a>
<a class="video-rebind a-btn" href="#balabala">重新绑定 video</a>
</div>
<style>
.fixed-container {
position: fixed;
left: 20px;
top: 50px;
width: 140px;
height: 80px;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-content:space-around;
background-color: #fce4dc;
border-radius: 5%;
border: 3px solid pink;
text-align: center;
}
.rate-input {
display: inline-block;
width: 40px;
padding: 3px;
}
.a-btn {
display: inline-block;
background-color: #999;
color: aliceblue;
padding: 3px;
border-radius: 5%;
transition: all .2s ease;
text-decoration: none;
}
.a-btn:active {
background-color: #444;
}
</style>
`
document.body.appendChild(fixedBar)
fixedBar.addEventListener('click', function (ev) {
var target = ev.target
switch (true) {
// 修改倍率按钮
case target.className.indexOf('rate-change') > -1 :
var val = fixedBar.querySelector('.rate-input').value
if (val > 16) fixedBar.querySelector('.rate-input').value = val = 16
_this.changeSpeed(val)
break
// 重新绑定 video 按钮
case target.className.indexOf('video-rebind') > -1 :
_this.bindPlayer()
break
}
})
return this
}
// 关闭跳出限制,暂时无法实现,因为无法移除匿名的二级事件监听函数
this.freeMouse = function() {
return this
}
// 控制速度
this.changeSpeed = function (rate) {
ifrDoc.querySelector('#video_html5_api').playbackRate = Number(rate) || 1
return this
}
}
})()<file_sep># Introduction
浏览器脚本,可加速广工工程伦理网课的播放速度
# Usage
页面加载完成之后,将脚本复制到控制台运行即会出现悬浮工具框
- 设置倍率,默认是八倍,最高十六倍
- **切换视频后要重新绑定 video**
- 建议在控制台找到 video 标签的 EventListeners 并将 `mouseout` 的事件监听 `remove` 掉,解放鼠标
|
207e405910d7406993733860fbcdab69bace8b1b
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
AymaxLi/online-course-speed-up
|
481f576c1ca92e2adb7f4dc8b5711dcfc3fadcd5
|
9e48b94d4f4a957c2897e0bc8fa4e79d1f2583ac
|
refs/heads/main
|
<file_sep># secure-golang coding workshop
Simple API based Web App using golang gorilla mux to demonstrate security mechanism implementations
Following are the security mechanisms implemented in the app
- https connection
- JWT authentication mechanism
- Secret (jwt key) values are stored in env variables
- JWT signing method is verified
- Token cookie is on only my domain localhsot
- Token expires after a period of time
- Token expires after logout
- Token is stored using HttpOnly cookie
- Password are hashed and salted
- Server side input validation
- Password complexity checks
- CSRF protection
- Logging events to syslog/logfile
- Cookie values expires and deleted from browser
- Autocomplete="off" for html sensitive input box
- Rate limit protection
- Disabling Caching
- .gitignore: keys, .env, and database
## Discussion
There are assumptions made for the nature of application.
- Assumption: users are entering data in the form that may belong to them or any other person. Thererfore the form allows to enter email and name even they are not matching the logged in user info.
- Secret values are stored in environment variables, However for complex envirnment it is always recomended to use secret manager such as Vault or AWS Secrets Manager
- HTTPs uses self signed certificates just to stress on the importance of encrypted traffic, however certs should be always generated from CA. Let's encrypt is a good option for such demo. Implementation will not change for both CA signed or self-signed certs. Bad certificate notice will appear because the certificate is not fixed for ip, you should ignore this message for localhost development.
- Tokens expire after a period of time, 10 min in this app. There are services where sessions last for long time, this is how Twitter, Github, Gmail work. The assumption is that the user should logout if he wants to terminate the session. In this app both logout and expiry time are implemented. Based on the criticality of the service, token expiry time is set.
- Blacklisted tokens due to logout functionality can be deleted after they expiry using database stored procedures. both token and expiry timestamp are stored in the same table.
- For sake of making the app setup easy, Sqlite database is used, there are no credentials to access the database since it's stored locally on the server, but for remote databases such as mysql, postgress ...etc. Database should be secured with strong password.
- Security analysts keep their jobs because of logs. The app implemented simple logging mechanism for major events such as user created, login success, login failure log out, message sent ..etc. It's always recommend to support logging to facilitate sending the logs to SIEM such as Splunk or ELK
- Rate limit is implemented on login page only as a demo, it offers protection against bruteforcing and also protect the server utilization. Locking down the user sending too many request is not implemented, it can be done using WAF. The current implementation does not limit by ip address since it's a localhost demo. It protects the overall function from being called too many times within time frame. The same can be done using username if the purpose is not security rather API billing.
- Extra client side input validation checks could be added to improve user's experience however, they are ignored since they have been taken care of at the server side for security purpose
**Setup instructions are for Linux systems**. Golang 1.15
Follow the steps blow and execute the given commands by copy paste to your terminal
First make sure you have go1.15+ installed
```sh
go version
```
you should see something like
```sh
go version go1.15 linux/amd64
```
## Clone the repo
```sh
cd $HOME/go/src
git clone https://github.com/alwashali/secure-golang-web-app-demo
cd secure-golang-web-app-demo/
```
## Generate ssl certificates
```sh
mkdir keys
openssl genrsa -out keys/server.key 2048
openssl req -new -x509 -sha256 -key keys/server.key -out keys/server.crt -days 3650
```
## Create .env file
Create .env file which will be used for loading the keys to OS environment variables. You should put your 32 character long keys inside .env file.
```sh
echo "KEY={replace with your 32 character KEY}" > .env
echo "CSRFKEY={replace with your 32 character CSRFKEY key}" >> .env
```
## Run
```sh
go run main.go
```
## Logs
Once you are in and enjoying the cat video, then create a new user by visiting https://localhost:8080/signup
Ater using the app, you can see the logs stored in logs.txt
```sh
cat logs.txt
```
<file_sep>package utils
import (
"errors"
"fmt"
"moneylion_assignmnet/dbUtils"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
// Key hold environment Variable KEY.
// Values are loaded to system using gotenv package from .env
var Key = os.Getenv("KEY")
// CSRFKey used by gorilla/csrf
var CSRFKey = os.Getenv("CSRFKEY")
// Generate JWT token for authentication and authorization
// verify https://jwt.io/
func GenerateToken(username string) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["username"] = username
claims["exp"] = time.Now().Add(time.Minute * 10).Unix()
tokenString, err := token.SignedString([]byte(Key))
if err != nil {
fmt.Errorf("Error %s", err.Error())
return "", err
}
return tokenString, nil
}
func HashPasswored(pass []byte) string {
hash, err := bcrypt.GenerateFromPassword(pass, bcrypt.MinCost)
if err != nil {
panic(err)
}
return string(hash)
}
// Validate is Manually Validating input using regular expressions
// Inputtype tells the type of string to be validated
func Validate(InputType string, value string) bool {
if len(value) > 0 && len(value) < 100 {
// golang does not support lookahead regex
// Regex returns false if empty
// All input validation here
usernameRegex := regexp.MustCompile("^[A-Za-z0-9]+$")
emailRegex := regexp.MustCompile("^[A-Za-z0-9.]+[@]+[A-Za-z0-9]+[.]+[A-Za-z0-9]+$")
dateRegex := regexp.MustCompile("^[0-9][0-9][/][0-9][0-9][/][0-9][0-9][0-9][0-9]$")
ssnRegex := regexp.MustCompile("^[0-9][0-9][0-9][-][0-9][0-9][-][0-9][0-9][0-9][0-9]$")
//password check
num := `[0-9]{1}`
az := `[a-z]{1}`
AZ := `[A-Z]{1}`
symbol := `[!@#~$%^&*()+|_]{1}`
switch InputType {
case "username":
if usernameRegex.MatchString(value) {
return true
}
return false
case "email":
if emailRegex.MatchString(value) {
return true
}
return false
case "password":
// password max size already verified above
if len(value) >= 8 {
if b, _ := regexp.MatchString(num, value); b {
if b, _ := regexp.MatchString(az, value); b {
if b, _ := regexp.MatchString(AZ, value); b {
if b, _ := regexp.MatchString(symbol, value); b {
return true
}
}
}
}
return false
}
return false
case "ssn":
if ssnRegex.MatchString(value) {
return true
}
return false
case "dob":
if dateRegex.MatchString(value) {
date := strings.Split(value, "/")
days, _ := strconv.Atoi(date[0])
months, _ := strconv.Atoi(date[1])
years, _ := strconv.Atoi(date[2])
if days > 0 && days <= 31 && months <= 12 && months >= 1 && years >= 1900 {
return true
}
}
return false
}
} else {
return false
}
return true
}
// VerifyToken send by protecting middleware function
func VerifyToken(bearerToken string) bool {
token, error := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error, unexpected signing method")
}
return []byte(Key), nil
})
if error != nil {
return false
}
db := dbUtils.ConnectDB()
defer db.Close()
blacktoken := dbUtils.TokenBlackList{}
if token.Valid && db.Where("token= ?", token.Raw).First(&blacktoken).RecordNotFound() {
return true
}
return false
}
// GetTokenOwner extract token from request and return the username
func GetTokenOwner(r *http.Request) (string, error) {
if ok := strings.Contains(r.Header.Get("Cookie"), "Authorization"); ok {
authorizationCookie, err := r.Cookie("Authorization")
if err != nil {
fmt.Println("Error getting the authcookie", err)
}
if authorizationCookie.Value != "" {
bearerToken := strings.Split(authorizationCookie.Value, " ")
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(bearerToken[1], claims, func(token *jwt.Token) (interface{}, error) {
return []byte(Key), nil
})
if err != nil {
return "", errors.New("Error parsing the token")
}
if token.Valid {
// do something with decoded claims
for key, val := range claims {
if key == "username" {
return val.(string), nil
}
}
}
}
}
return "", errors.New("Error parsing the token")
}
// BlackListToken invalidate token when logout
// Useful when logout before expiry time
func BlackListToken(btoken string) bool {
expiryTime := ""
db := dbUtils.ConnectDB()
defer db.Close()
claims := jwt.MapClaims{}
parsedToken, _ := jwt.ParseWithClaims(btoken, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(Key), nil
})
if parsedToken.Valid {
for key, val := range claims {
if key == "exp" {
expTimeInt64, _ := val.(float64)
expiryTime = time.Unix(int64(expTimeInt64), 0).String()
}
}
}
db.Create(&dbUtils.TokenBlackList{Token: btoken, ExpiredAt: expiryTime})
return true
}
<file_sep>module moneylion_assignmnet
go 1.15
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gorilla/csrf v1.7.0
github.com/gorilla/mux v1.8.0
github.com/jinzhu/gorm v1.9.16
github.com/stretchr/testify v1.7.0 // indirect
github.com/subosito/gotenv v1.2.0
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324
)
<file_sep>package main
import (
"fmt"
"log"
"moneylion_assignmnet/controllers"
"moneylion_assignmnet/dbUtils"
"moneylion_assignmnet/loger"
"moneylion_assignmnet/utils"
"net/http"
"os"
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
"github.com/subosito/gotenv"
)
func init() {
err := gotenv.Load()
if err != nil {
fmt.Printf(".env not found\n\n")
os.Exit(1)
}
}
func runServer() {
// rate limit
route := mux.NewRouter().StrictSlash(true)
// static route for css
filesystem := http.FileServer(http.Dir("./templates/css"))
route.PathPrefix("/templates/css").Handler(http.StripPrefix("/templates/css", filesystem))
// All app routes
route.HandleFunc("/", controllers.MainPage).Methods("GET")
// Login page, view login form page
route.HandleFunc("/login", controllers.LoginPage).Methods("GET")
// Login POST for actual login
route.HandleFunc("/login", controllers.SignIn).Methods("POST")
route.HandleFunc("/signup", controllers.SignUpPage).Methods("GET")
route.HandleFunc("/signup", controllers.SignUp).Methods("POST")
route.HandleFunc("/contact", controllers.VerifyAccess(controllers.SendMessage)).Methods("POST")
route.HandleFunc("/contactform", controllers.VerifyAccess(controllers.Contactus)).Methods("GET")
route.HandleFunc("/logout", controllers.Logout).Methods("GET")
fmt.Println("Up and Running => https://localhost:8080")
// logging
loger.Logit("Server started")
log.Fatal(http.ListenAndServeTLS(":8080", "keys/server.crt", "keys/server.key", csrf.Protect([]byte(utils.CSRFKey))(route)))
}
func main() {
dbUtils.InitialMigration()
runServer()
}
<file_sep>package loger
import (
"fmt"
"log"
"os"
"time"
)
// Logit logs important event to log file
func Logit(logContent string) {
file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
timestamp := time.Now().Format("2006-01-02 15:04:05")
log := fmt.Sprintf("%s %s \n", timestamp, logContent)
file.WriteString(log)
}
<file_sep>package controllers
import (
"encoding/json"
"fmt"
"html/template"
"moneylion_assignmnet/dbUtils"
"moneylion_assignmnet/loger"
"moneylion_assignmnet/utils"
"net/http"
"strings"
"time"
"github.com/gorilla/csrf"
"golang.org/x/crypto/bcrypt"
"golang.org/x/time/rate"
)
// routes functions
func MainPage(w http.ResponseWriter, r *http.Request) {
data := ""
t2, err := template.ParseFiles("templates/Index.html")
if err != nil {
fmt.Println(err)
}
err = t2.Execute(w, data)
if err != nil {
fmt.Println(err)
}
}
// LoginPage form (GET)
func LoginPage(w http.ResponseWriter, r *http.Request) {
// what if he is already logged in
// redirect to contactform page
// fmt.Println(r.Header.Get("Cookie"))
w.Header().Set("X-CSRF-Token", csrf.Token(r))
w.Header().Set("cache-control", "no-cache, no-store, must-revalidate")
if ok := strings.Contains(r.Header.Get("Cookie"), "Authorization"); ok {
authorizationCookie, err := r.Cookie("Authorization")
if err != nil {
fmt.Println("Error getting the authorizationCookie", err)
return
}
if authorizationCookie.Value != "" {
bearerToken := strings.Split(authorizationCookie.Value, " ")
if len(bearerToken) == 2 {
valid := utils.VerifyToken(bearerToken[1])
if valid {
http.Redirect(w, r, "https://"+r.Host+"/contactform", http.StatusTemporaryRedirect)
return
}
}
}
}
// Not logged in, render normal login form
t, err := template.ParseFiles("templates/login.html")
if err != nil {
fmt.Println(err)
}
err = t.Execute(w, map[string]interface{}{csrf.TemplateTag: csrf.TemplateField(r)})
if err != nil {
fmt.Println(err)
}
}
// SignUp API POST
func SignUp(w http.ResponseWriter, r *http.Request) {
var u dbUtils.User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&u); err != nil {
fmt.Fprintln(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
if utils.Validate("email", u.Email) && utils.Validate("username", u.Username) && utils.Validate("password", u.Password) {
db := dbUtils.ConnectDB()
defer db.Close()
// if user does not exist
if db.Where("username= ?", strings.ToLower(u.Username)).First(&u).RecordNotFound() {
HashedPassword := utils.HashPasswored([]byte(u.Password))
user := &dbUtils.User{
Username: strings.ToLower(u.Username),
Password: <PASSWORD>,
Email: u.Email,
}
db.Create(&user)
// logging
loger.Logit(fmt.Sprintf("%s %s", "New User Registered: ", user.Username))
fmt.Fprintf(w, "Success, You can login now")
} else { // end of if db.where
fmt.Fprintln(w, "User Already exist")
}
} else { // end of if Validate
message := `
Fill all the fields correctly, double check the
password, it must contains at least one
Upper case,
Lower case,
Number,
Special characters
`
fmt.Fprintln(w, message)
}
}
// SignUpPage GET shows the signup form
func SignUpPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-CSRF-Token", csrf.Token(r))
t2, err := template.ParseFiles("templates/signup.html")
if err != nil {
fmt.Println(err)
}
err = t2.Execute(w, map[string]interface{}{csrf.TemplateTag: csrf.TemplateField(r)})
if err != nil {
fmt.Println(err)
}
}
// Logout deletes cookie from client and redirect to home page
func Logout(w http.ResponseWriter, r *http.Request) {
c := http.Cookie{
Name: "Authorization",
Value: " ",
HttpOnly: true,
Domain: "localhost",
// set cookie in the past to be deleted from browser
Expires: time.Now().Add(time.Hour * -24),
}
http.SetCookie(w, &c)
// logging
user, err := utils.GetTokenOwner(r)
if err == nil {
loger.Logit(fmt.Sprintf("%s %s", user, " logged out"))
}
if ok := strings.Contains(r.Header.Get("Cookie"), "Authorization"); ok {
authorizationCookie, err := r.Cookie("Authorization")
if err != nil {
fmt.Println("Error getting the JWT cookie", err)
}
if authorizationCookie.Value != "" {
bearerToken := strings.Split(authorizationCookie.Value, " ")
if len(bearerToken) == 2 {
blacklisted := utils.BlackListToken(bearerToken[1])
if !blacklisted {
fmt.Println("Error blacklisting token", err)
}
}
}
}
http.Redirect(w, r, "https://"+r.Host, http.StatusSeeOther)
return
}
var limiter = rate.NewLimiter(rate.Every(10*time.Second), 10)
// SignIn api (Post)
func SignIn(w http.ResponseWriter, r *http.Request) {
if limiter.Allow() == false {
http.Error(w, http.StatusText(429), http.StatusTooManyRequests)
return
}
var u dbUtils.User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&u); err != nil {
fmt.Fprintln(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
db := dbUtils.ConnectDB()
defer db.Close()
if utils.Validate("username", u.Username) {
user := dbUtils.User{}
if db.Where("username= ?", strings.ToLower(u.Username)).First(&user).RecordNotFound() {
// logging
loger.Logit("Failed Login, user does not exist")
http.Error(w, "User Does not exist", http.StatusUnauthorized)
return
}
//verify password
ComparedPassword := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(u.Password))
if ComparedPassword == bcrypt.ErrMismatchedHashAndPassword && ComparedPassword != nil {
w.WriteHeader(http.StatusUnauthorized)
// logging
loger.Logit(fmt.Sprintf("%s %s", user.Username, "failed to login"))
fmt.Fprintf(w, "Failed Login")
return
}
token, err := utils.GenerateToken(user.Username)
if err != nil {
fmt.Println("Error Generating token")
panic(err)
}
c := http.Cookie{
Name: "Authorization",
Value: "Bearer " + token,
HttpOnly: true,
Domain: "localhost",
Expires: time.Now().Add(time.Minute * 10),
Secure: true,
Path: "/",
}
http.SetCookie(w, &c)
// logging
loger.Logit(fmt.Sprintf("%s %s", u.Username, ": Successful Login"))
fmt.Fprintf(w, "Success")
return
}
w.WriteHeader(http.StatusUnauthorized)
// logging
loger.Logit(fmt.Sprintf("%s %s", u.Username, " Failed Login"))
fmt.Fprintf(w, "Failed Login")
}
// SendMessage Actual POST API
func SendMessage(w http.ResponseWriter, r *http.Request) {
var msg dbUtils.Message
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
if err := decoder.Decode(&msg); err != nil {
fmt.Fprintln(w, http.StatusBadRequest, "Invalid request payload")
return
}
if utils.Validate("email", msg.Email) && utils.Validate("username", msg.Name) && utils.Validate("ssn", msg.SSN) && utils.Validate("dob", msg.DOB) {
user, err := utils.GetTokenOwner(r)
if err != nil {
fmt.Fprintf(w, "Error")
return
}
db := dbUtils.ConnectDB()
defer db.Close()
db.Create(&dbUtils.Message{Name: msg.Name, DOB: msg.DOB, Email: msg.Email, SSN: msg.SSN, EnteredBy: user})
//logging
loger.Logit(fmt.Sprintf("%s %s", user, "added new message"))
//send response
fmt.Fprintf(w, "Sent Successfully")
return
}
fmt.Fprintf(w, "Invalid Input Format")
return
}
// Contactus page
func Contactus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-CSRF-Token", csrf.Token(r))
w.Header().Set("cache-control", "no-cache, no-store, must-revalidate")
t, err := template.ParseFiles("templates/contactform.html")
if err != nil {
fmt.Println(err)
}
err = t.Execute(w, map[string]interface{}{csrf.TemplateTag: csrf.TemplateField(r)})
if err != nil {
fmt.Println(err)
}
}
// VerifyAccess checks token is valid and not expired
func VerifyAccess(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if cookie Authorization exists
if ok := strings.Contains(r.Header.Get("Cookie"), "Authorization"); ok {
authorizationCookie, err := r.Cookie("Authorization")
if err != nil {
fmt.Println("Error getting the authcookie", err)
}
if authorizationCookie.Value != "" {
bearerToken := strings.Split(authorizationCookie.Value, " ")
if len(bearerToken) == 2 {
if valid := utils.VerifyToken(bearerToken[1]); valid {
next(w, r)
} else {
http.Redirect(w, r, "https://"+r.Host+"/login", http.StatusTemporaryRedirect)
}
}
}
} else {
// Auth is not found
// Redirect to login for authentication
http.Redirect(w, r, "https://"+r.Host+"/login", http.StatusTemporaryRedirect)
}
}) // ( closing of HandlerFunc
}
<file_sep>package dbUtils
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var database *gorm.DB
var err error
// TokenBlackList contains blacklisted tokens due to logout before expiry time
type TokenBlackList struct {
Token string
ExpiredAt string
}
// Message data structure for contact us form
type Message struct {
gorm.Model
Name string `json:"name"`
Email string `json:"email"`
DOB string `json:"dob"`
SSN string `json:"ssn"`
EnteredBy string
}
// User data structure for loging
type User struct {
gorm.Model
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
Email string `json:"email"`
}
// ConnectDB returns a database connector object
//Credentials if exist should be put in .env file
func ConnectDB() *gorm.DB {
db, err := gorm.Open("sqlite3", "database.sqlite3")
if err != nil {
panic("Database Connection Error")
}
return db
}
// InitialMigration setup the tables
func InitialMigration() {
database, err = gorm.Open("sqlite3", "database.sqlite3")
if err != nil {
fmt.Println(err.Error())
panic("Opps, Failed to connect to database")
}
defer database.Close()
database.AutoMigrate(&Message{}, &User{}, &TokenBlackList{})
}
|
af919926034f7ae913f533ee403bb6f08d3040f6
|
[
"Go Module",
"Markdown",
"Go"
] | 7 |
Go Module
|
alwashali/secure-golang-web-app-demo
|
688b1b09b82b018c9c92ea2a4a80d3a3005d7a21
|
98ff33a6a544b66e08e8fc5928dba80ec54e3719
|
refs/heads/master
|
<file_sep>// <NAME>
//250748631
//<EMAIL>
//CS3388 Assignment 4
//Create a scene with three spheres bouncing on a plane that has been drawn with ray casting
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
//Equation for a sphere
//(x-x_0)^2+(y-y_0)^2+(z-z_0)^2=R^2.
//Spheres bounce min and max heights. When hit or go over this point, switch directions
#define MAX_HEIGHT 5.0
#define MIN_HEIGHT 0.0
//Coordinates for the screen size to be used for ray casting
#define WINDOW_POSITION_X 0.0
#define WINDOW_POSITION_Y 0.0
#define SCREEN_WIDTH 500.0
#define SCREEN_HEIGHT 500.0
#define NUMBER_OF_SPHERES 3
//Camera Values (at.x, at.y, at.z, lookat.x, lookat.y, lookat.z, up.x, up.y, up.z)
//Simulated Camera Values
float cameraValues[] = { 0.0, 3.0, -10.0, 0, 0, 0, 0, 1, 0 };
float distanceFromCamToView = -5.0;
//The camera values for the real camera
float realCameraValues[] = { 0, 0, 1, 0, 0, 0, 0, 1, 0 };
//View max and min cordinates
float uMin = -2.5;
float uMax = 2.5;
float vMin = 0.0;
float vMax = 5.0;
//Light source in the scene
float lightSource[] = { -7.0, 5.0, -10.0 };
//Shading factors
float diffuse = 0.3;
float ambient = 0.2;
float specular = 0.5;
float reflectiveness = 5.0;
float lightIntensity = 1.0;
//Variables for the ground
float groundColour[3] = { 1.0, 1.0, 1.0 };
//Error value for fixing precision issues with shadows
float shadowError = 0.01;
//Class for sphere
class Sphere
{
private:
float radius;
float speed;
float colour[3];
int direction;
float position[3];
public:
Sphere()
{
this->radius = 1.0;
this->position[0] = 0.0;
this->position[1] = 0.0;
this->position[2] = 0.0;
this->speed = 0.0;
this->colour[0] = 1.0;
this->colour[1] = 1.0;
this->colour[2] = 1.0;
direction = 1;
}
Sphere(float radius, float x, float y, float z, float speed, float colour1, float colour2, float colour3)
{
this->radius = radius;
this->position[0] = x;
this->position[1] = y;
this->position[2] = z;
this->speed = speed;
this->colour[0] = colour1;
this->colour[1] = colour2;
this->colour[2] = colour3;
direction = 1;
};
//Increase the spheres position by its speed value in the direction of its direction value
void move()
{
position[1] += (direction * speed);
//Check if need switch directions
if (direction > 0 && position[1] + radius >= MAX_HEIGHT)
{
direction *= -1;
}
if (direction < 0 && position[1] - radius <= MIN_HEIGHT)
{
direction *= -1;
}
}
float getXPos()
{
return position[0];
}
float getYPos()
{
return position[1];
}
float getZPos()
{
return position[2];
}
float getRadius()
{
return radius;
}
float getRed()
{
return colour[0];
}
float getGreen()
{
return colour[1];
}
float getBlue()
{
return colour[2];
}
};
//Create the 3 sphere objects
Sphere mySpheres[NUMBER_OF_SPHERES] = { Sphere(0.66, -1.5, 2.0, -3.0, 0.3, 0.0, 1.0, 0.0), Sphere(1.00, 0.0, 2.0, 0.0, 0.2, 1.0, 0.0, 0.0), Sphere(1.33, 1.5, 2.0, 3.0, 0.1, 0.0, 0.0, 1.0) };
void drawWithRayCasting()
{
//Ray from the eye through the pixil in the viewport
float ray[3];
float underSquareRoot[3]; //The ab and c under the square root in the equation
//w = -(lookat - eye) / ||g||
float g[3];
g[0] = -1 * (cameraValues[3] - cameraValues[0]);
g[1] = -1 * (cameraValues[4] - cameraValues[1]);
g[2] = -1 * (cameraValues[5] - cameraValues[2]);
float gMag = sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);
float w[3];
w[0] = g[0] / gMag;
w[1] = g[1] / gMag;
w[2] = g[2] / gMag;
//Convert to viewing to find the viewing plane
//u = t x w / ||t x w||
float u[3];
u[0] = (cameraValues[7] * w[2] - cameraValues[8] * w[1]);
u[1] = (cameraValues[8] * w[0] - cameraValues[6] * w[2]);
u[2] = (cameraValues[6] * w[1] - cameraValues[7] * w[0]);
float uMag = sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]);
u[0] = u[0] / uMag;
u[1] = u[1] / uMag;
u[2] = u[2] / uMag;
//v = w x u
float v[3];
v[0] = w[1] * u[2] - w[2] * u[1];
v[1] = w[2] * u[0] - w[0] * u[2];
v[2] = w[0] * u[1] - w[1] * u[0];
//V2W -> u[x] v[x] w[x] e[x] * point
// u[y] v[y] w[y] e[y]
// u[z] v[z] w[z] e[z]
// 0 0 0 1
//For Every Pixil
for (float y = 0; y < SCREEN_HEIGHT; y++)
{
for (float x = 0; x < SCREEN_WIDTH; x++)
{
//Pixil in world Space
float pixilView[3];
float pixilWorld[3];
//Note depth in pixil world will always be zero
//Also take from the center of the pixil
//ray p(t) = e + td
//Viewport to view
pixilView[0] = ((x + 0.5) - 0) * ((uMax - (uMin)) / (SCREEN_WIDTH - (-0))) + (uMin);
pixilView[1] = ((y + 0.5) - 0) * ((vMax - (vMin)) / (SCREEN_HEIGHT - (-0))) + (vMin);
pixilView[2] = distanceFromCamToView;
//View to world
pixilWorld[0] = u[0] * pixilView[0] + v[0] * pixilView[1] + w[0] * pixilView[2] + cameraValues[0];
pixilWorld[1] = u[1] * pixilView[0] + v[1] * pixilView[1] + w[1] * pixilView[2] + cameraValues[1];
pixilWorld[2] = u[2] * pixilView[0] + v[2] * pixilView[1] + w[2] * pixilView[2] + cameraValues[2];
//Values for keeping track of the closest sphere
float closestT = 1;
int closestSphere = -1;
float closestPosition[3];
//Construct a ray from the eye through viewport (at 0,0)
ray[0] = pixilWorld[0] - cameraValues[0];
ray[1] = pixilWorld[1] - cameraValues[1];
ray[2] = pixilWorld[2];
//Values for the ab and c variables in the equation for finding how many points a ray interects a sphere
//a = ||d|| ^ 2
//b = ed
//c = ||e||^2 - 1
//For every object in the scene
for (int sphereIndex = 0; sphereIndex < NUMBER_OF_SPHERES; sphereIndex++)
{
//Find intersecction with the ray
//Find the ab and c values using the ray and the sphere
underSquareRoot[0] = ray[0] * ray[0] + ray[1] * ray[1] + ray[2] * ray[2];
underSquareRoot[1] = 2 * ray[0] * (cameraValues[0] - mySpheres[sphereIndex].getXPos()) + 2 * ray[1] * (cameraValues[1] - mySpheres[sphereIndex].getYPos()) + 2 * ray[2] * (cameraValues[2] - mySpheres[sphereIndex].getZPos());
underSquareRoot[2] = mySpheres[sphereIndex].getXPos() * mySpheres[sphereIndex].getXPos() + mySpheres[sphereIndex].getYPos() * mySpheres[sphereIndex].getYPos() + mySpheres[sphereIndex].getZPos() * mySpheres[sphereIndex].getZPos() + cameraValues[0] * cameraValues[0] + cameraValues[1] * cameraValues[1] + cameraValues[2] * cameraValues[2] + -2 * (mySpheres[sphereIndex].getXPos() * cameraValues[0] + mySpheres[sphereIndex].getYPos() * cameraValues[1] + mySpheres[sphereIndex].getZPos() * cameraValues[2]) - mySpheres[sphereIndex].getRadius() * mySpheres[sphereIndex].getRadius();
float underSquareRootValue = underSquareRoot[1] * underSquareRoot[1] - 4 * underSquareRoot[0] * underSquareRoot[2];
//If > 0, intersect at 2 points. If == 0, grazes a point. If <0, completely misses
if (underSquareRootValue > 0)
{
//Ray intersects sphere in two points
//+/- for the two points. The closer point (the one closer to the camera), will be the negative square root
float tValue = (underSquareRoot[1] - sqrt(underSquareRoot[1] * underSquareRoot[1] - 4 * underSquareRoot[0] * underSquareRoot[2])) / (2 * underSquareRoot[0]);
//Keep closest sphere to the camera, meaning the lowest t value
if (closestSphere == -1 || tValue < closestT)
{
closestT = tValue;
closestSphere = sphereIndex;
closestPosition[0] = cameraValues[0] + tValue * -1 * ray[0];
closestPosition[1] = cameraValues[1] + tValue * -1 * ray[1];
closestPosition[2] = cameraValues[2] + tValue * -1 * ray[2];
}
}
}
//Only draw the closest sphere because any other spheres will be obsured
if (closestSphere >= 0)
{
//Normal. just consider the point thats hit as a vector (for a generic sphere) So minus its xyz cordnates to get back to the origin. Also normalize the vector
float normal[3];
normal[0] = (closestPosition[0] - mySpheres[closestSphere].getXPos()) / mySpheres[closestSphere].getRadius();
normal[1] = (closestPosition[1] - mySpheres[closestSphere].getYPos()) / mySpheres[closestSphere].getRadius();
normal[2] = (closestPosition[2] - mySpheres[closestSphere].getZPos()) / mySpheres[closestSphere].getRadius();
float normalMag = sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]);
normal[0] = normal[0] / normalMag;
normal[1] = normal[1] / normalMag;
normal[2] = normal[2] / normalMag;
//Light unit vector from the point to the light
float lightVector[3];
lightVector[0] = lightSource[0] - closestPosition[0];
lightVector[1] = lightSource[1] - closestPosition[1];
lightVector[2] = lightSource[2] - closestPosition[2];
float lightMag = sqrt(lightVector[0] * lightVector[0] + lightVector[1] * lightVector[1] + lightVector[2] * lightVector[2]);
lightVector[0] = lightVector[0] / lightMag;
lightVector[1] = lightVector[1] / lightMag;
lightVector[2] = lightVector[2] / lightMag;
//Find the light intensity (normals dot product with the light direction)
float intensity = normal[0] * lightVector[0] + normal[1] * lightVector[1] + normal[2] * lightVector[2];
//Add the specular phong highlights
// R = -L + 2(N dot L) * N
float R[3];
R[0] = -1 * lightVector[0] + 2 * intensity * normal[0];
R[1] = -1 * lightVector[1] + 2 * intensity * normal[1];
R[2] = -1 * lightVector[2] + 2 * intensity * normal[2];
//I = KI(R dot V)^n
float viewMag = sqrt(ray[0] * ray[0] + ray[1] * ray[1] + ray[2] * ray[2]);
float view[3];
view[0] = ray[0] / viewMag;
view[1] = ray[1] / viewMag;
view[2] = ray[2] / viewMag;
float specularIntensity = specular * pow((R[0] * view[0] + R[1] * view[1] + R[2] * view[2]), reflectiveness);
//See if the object is obsurded so its in shadow
bool inShadow = false;
//Form a ray from the point to the light source
float shadowRay[3];
shadowRay[0] = lightSource[0] - closestPosition[0];
shadowRay[1] = lightSource[1] - closestPosition[1];
shadowRay[2] = lightSource[2] - closestPosition[2];
//To account for shadow precision error
closestPosition[0] = closestPosition[0] - shadowError * shadowRay[0];
closestPosition[1] = closestPosition[1] - shadowError * shadowRay[1];
closestPosition[2] = closestPosition[2] - shadowError * shadowRay[2];
float groundUnderSquareRoot[3];
//Check if intercept a sphere. If so, only draw the ambient lighted colour. If not, ambient, specular, and diffuse.
//Check all the objects
for (int sphereIndex = 0; sphereIndex < NUMBER_OF_SPHERES; sphereIndex++)
{
//Stop colliding with itself
if (sphereIndex == closestSphere)
{
continue;
}
//Calculate the square root value
groundUnderSquareRoot[0] = shadowRay[0] * shadowRay[0] + shadowRay[1] * shadowRay[1] + shadowRay[2] * shadowRay[2];
groundUnderSquareRoot[1] = 2 * shadowRay[0] * (closestPosition[0] - mySpheres[sphereIndex].getXPos()) + 2 * shadowRay[1] * (closestPosition[1] - mySpheres[sphereIndex].getYPos()) + 2 * shadowRay[2] * (closestPosition[2] - mySpheres[sphereIndex].getZPos());
groundUnderSquareRoot[2] = mySpheres[sphereIndex].getXPos() * mySpheres[sphereIndex].getXPos() + mySpheres[sphereIndex].getYPos() * mySpheres[sphereIndex].getYPos() + mySpheres[sphereIndex].getZPos() * mySpheres[sphereIndex].getZPos() + closestPosition[0] * closestPosition[0] + closestPosition[1] * closestPosition[1] + closestPosition[2] * closestPosition[2] + -2 * (mySpheres[sphereIndex].getXPos() * closestPosition[0] + mySpheres[sphereIndex].getYPos() * closestPosition[1] + mySpheres[sphereIndex].getZPos() * closestPosition[2]) - mySpheres[sphereIndex].getRadius() * mySpheres[sphereIndex].getRadius();
float underSquareRootValueGround = groundUnderSquareRoot[1] * groundUnderSquareRoot[1] - 4 * groundUnderSquareRoot[0] * groundUnderSquareRoot[2];
//Intercects a sphere
if (underSquareRootValueGround > 0)
{
//Make sure the point is atually infront the point
float tValueShadow = (groundUnderSquareRoot[1] - sqrt(groundUnderSquareRoot[1] * groundUnderSquareRoot[1] - 4 * groundUnderSquareRoot[0] * groundUnderSquareRoot[2])) / (2 * groundUnderSquareRoot[0]);
if (tValueShadow < 0)
{
//Point is obsured from the light source, so it is in shadow
inShadow = true;
//Found that the sphere is already in shadow. No need to check the remaining objects
break;
}
}
}
//Find the final colour
float finalColour[3];
if (inShadow)
{
finalColour[0] = ambient * mySpheres[closestSphere].getRed();
finalColour[1] = ambient * mySpheres[closestSphere].getGreen();
finalColour[2] = ambient * mySpheres[closestSphere].getBlue();
}
else
{
finalColour[0] = ambient * mySpheres[closestSphere].getRed() + diffuse * lightIntensity * intensity * mySpheres[closestSphere].getRed() + specularIntensity * mySpheres[closestSphere].getRed();
finalColour[1] = ambient * mySpheres[closestSphere].getGreen() + diffuse * lightIntensity * intensity * mySpheres[closestSphere].getGreen() + specularIntensity * mySpheres[closestSphere].getGreen();
finalColour[2] = ambient * mySpheres[closestSphere].getBlue() + diffuse * lightIntensity * intensity * mySpheres[closestSphere].getBlue() + specularIntensity * mySpheres[closestSphere].getBlue();
}
//Draw the pixil
glPushMatrix();
glColor3f(finalColour[0], finalColour[1], finalColour[2]);
glBegin(GL_QUADS);
glVertex3f(x, y, 0);
glVertex3f(x, y + 1, 0);
glVertex3f(x + 1, y + 1, 0);
glVertex3f(x + 1, y, 0);
glEnd();
glPopMatrix();
}
else if (-1 * ray[1] < MIN_HEIGHT) //Ray didn't hit any spheres but may have hit ground plane. Check if the ray goes below the plane value and if it does the ground colour pixil
{
//Check if is actually being covered so is in shadow
bool inShadow = false;
//Form from the point to the light source
// = P + tL
float shadowRay[3];
//point = e + t(e-s). What t makes point.y = plane value.
//t = yvalue -e.y / (e.y - s.y)
float groundT = (MIN_HEIGHT - cameraValues[1]) / (ray[1]);
float groundPoint[3];
groundPoint[0] = cameraValues[0] + groundT * (ray[0]);
groundPoint[1] = cameraValues[1] + groundT * (ray[1]); //Should be zero
groundPoint[2] = cameraValues[2] + groundT * (ray[2]);
shadowRay[0] = lightSource[0] - groundPoint[0];
shadowRay[1] = lightSource[1] - groundPoint[1];
shadowRay[2] = lightSource[2] - groundPoint[2];
float groundUnderSquareRoot[3];
//Check if intercept a sphere. If so don't draw the pixil. If not, draw the ground pixil. If so, its obsured so its in shadow
for (int sphereIndex = 0; sphereIndex < NUMBER_OF_SPHERES; sphereIndex++)
{
groundUnderSquareRoot[0] = shadowRay[0] * shadowRay[0] + shadowRay[1] * shadowRay[1] + shadowRay[2] * shadowRay[2];
groundUnderSquareRoot[1] = 2 * shadowRay[0] * (groundPoint[0] - mySpheres[sphereIndex].getXPos()) + 2 * shadowRay[1] * (groundPoint[1] - mySpheres[sphereIndex].getYPos()) + 2 * shadowRay[2] * (groundPoint[2] - mySpheres[sphereIndex].getZPos());
groundUnderSquareRoot[2] = mySpheres[sphereIndex].getXPos() * mySpheres[sphereIndex].getXPos() + mySpheres[sphereIndex].getYPos() * mySpheres[sphereIndex].getYPos() + mySpheres[sphereIndex].getZPos() * mySpheres[sphereIndex].getZPos() + groundPoint[0] * groundPoint[0] + groundPoint[1] * groundPoint[1] + groundPoint[2] * groundPoint[2] + -2 * (mySpheres[sphereIndex].getXPos() * groundPoint[0] + mySpheres[sphereIndex].getYPos() * groundPoint[1] + mySpheres[sphereIndex].getZPos() * groundPoint[2]) - mySpheres[sphereIndex].getRadius() * mySpheres[sphereIndex].getRadius();
float underSquareRootValueGround = groundUnderSquareRoot[1] * groundUnderSquareRoot[1] - 4 * groundUnderSquareRoot[0] * groundUnderSquareRoot[2];
//Intercects a sphere
if (underSquareRootValueGround > 0)
{
inShadow = true;
break;
}
}
//Draw the pixil
glPushMatrix();
if (!inShadow)
{
glColor3f(groundColour[0], groundColour[1], groundColour[2]);
}
else
{
glColor3f(groundColour[0] * ambient, groundColour[1] * ambient, groundColour[2] * ambient);
}
glBegin(GL_QUADS);
glVertex3f(x, y, 0);
glVertex3f(x, y + 1, 0);
glVertex3f(x + 1, y + 1, 0);
glVertex3f(x + 1, y, 0);
glEnd();
glPopMatrix();
}
}
}
}
void display()
{
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
//Draw the sphere using ray casting
drawWithRayCasting();
glPopMatrix();
//Swap the buffer
glutSwapBuffers();
}
//Function to call of the functions needed to be called when idling
void idleFunctions()
{
//Move the spheres to their new positions
for (int i = 0; i < 3; i++)
{
mySpheres[i].move();
}
//Force a redraw to the screen
glutPostRedisplay();
}
//Set up the inital states of the scene
void init()
{
//Turn on depth
glEnable(GL_DEPTH_TEST);
//Set Black background
glClearColor(0.0, 0.0, 0.0, 1.0);
//Set up persepective
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//gluPerspective(60, 4/3, 1, 80);
glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -2, 2);
//Set Up Camera
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(realCameraValues[0], realCameraValues[1], realCameraValues[2], realCameraValues[3], realCameraValues[4], realCameraValues[5], realCameraValues[6], realCameraValues[7], realCameraValues[8]);
}
int main(int argc, char * argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT);
glutInitWindowPosition(WINDOW_POSITION_X + 100, WINDOW_POSITION_Y + 100);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutCreateWindow("CS3388 Assignment 4");
glutDisplayFunc(display);
glutIdleFunc(idleFunctions);
init();
glutMainLoop();
}
|
59314bafadb4c3f5887b5702937ee79b677ce140
|
[
"C++"
] | 1 |
C++
|
matthewchiborak/RayTracing
|
2cd8ed678f569e349f67dcc024d09f4fc707250f
|
08761c768897cad68d52d30649983710e903b9be
|
refs/heads/master
|
<repo_name>sanbon44/get1<file_sep>/geekbrains_4urok.js
/* Первое задание*/
/* function min(a,b){
(a < b) ? a : b;
}
console.log(min(0,10));*/
/*Второе задание*/
var str = '', b = 0, count = 0;
function countBs(str){
for (b = 0; b < str.length; b++){
if (str.charAt(b) =='b') count++;
}
return count;
}
str = prompt('Введите строку символов:' , str);
console.log('Символов "В" в приведенной строке: ' + countBs(str));
var str = '', i = 0, count = 0, simb = '';
function countChar(str,simb){
for (i = 0; i < str.length; i++){
if (str.charAt(i) ==simb) count++;
}
return count;
}
str = prompt('Введите строку символов:' , str);
simb = prompt('Какой символ ищем?' , simb)
console.log('В приведенной строке, искомых символов : ' + countChar(str, simb));
|
5b007b214a32e1d52597b3424d08c880760a0c5b
|
[
"JavaScript"
] | 1 |
JavaScript
|
sanbon44/get1
|
57dc5b29c63184b969fccc1b47ee9eaf4543662b
|
04a228513f0e0e4503d599c2d3810ed9103de42f
|
refs/heads/master
|
<repo_name>parthvadhadiya/live-face-recognition-using-resnet-model-load-with-dlib-library<file_sep>/face_reco.py
import dlib
import scipy.misc
import numpy as np
import os
import cv2
face_detector = dlib.get_frontal_face_detector()
shape_predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
face_recognition_model = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat')
TOLERANCE = 0.5
def get_face_encodings(path_to_image):
image = scipy.misc.imread(path_to_image)
detected_faces = face_detector(image, 1)
shapes_faces = [shape_predictor(image, face) for face in detected_faces]
return [np.array(face_recognition_model.compute_face_descriptor(image, face_pose, 1)) for face_pose in shapes_faces]
def compare_face_encodings(known_faces, face):
return (np.linalg.norm(known_faces - face, axis=1) <= TOLERANCE)
def find_match(known_faces, names, face):
matches = compare_face_encodings(known_faces, face)
count = 0
for match in matches:
if match:
return names[count]
count += 1
return 'Not Found'
video = cv2.VideoCapture(0)
image_filenames = filter(lambda x: x.endswith('.jpg'), os.listdir('images/'))
image_filenames = sorted(image_filenames)
paths_to_images = ['images/' + x for x in image_filenames]
face_encodings = []
for path_to_image in paths_to_images:
face_encodings_in_image = get_face_encodings(path_to_image)
if len(face_encodings_in_image) != 1:
print("Please change image: " + path_to_image + " - it has " + str(len(face_encodings_in_image)) + " faces; it can only have one")
exit()
face_encodings.append(get_face_encodings(path_to_image)[0])
names = [x[:-4] for x in image_filenames]
while True:
_ ,path_to_image = video.read()
cv2.imwrite('frame.jpg',path_to_image)
face_encodings_in_image = get_face_encodings('frame.jpg')
if os.path.exists('frame.jpg'):
os.remove('frame.jpg')
if len(face_encodings_in_image) != 1:
print("Please change image: " + path_to_image + " - it has " + str(len(face_encodings_in_image)) + " faces; it can only have one")
exit()
match = find_match(face_encodings, names, face_encodings_in_image[0])
print(path_to_image, match)
cv2.putText(path_to_image, match.capitalize(),
(5, path_to_image.shape[0] - 5),
cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.LINE_AA)
cv2.imshow('Video', path_to_image)
if cv2.waitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindows()
video.release()<file_sep>/README.md
# live-face-recognition-using-resnet-model-load-with-dlib-library
|
5e5f95cd7dfb1215661d0dfd634993f502bec2ae
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
parthvadhadiya/live-face-recognition-using-resnet-model-load-with-dlib-library
|
8b1d3a6015354e8b4f9537358c25713e9a2112f8
|
c98d5634decc7fc70d497045c2fa1b9a7084b0c8
|
refs/heads/master
|
<repo_name>punkeel/getenvy<file_sep>/.travis.yml
dist: xenial
language: c
compiler:
- clang
- gcc
addons:
apt:
packages:
- cppcheck
install:
- python -m pip install --user pygments restructuredtext-lint
script:
- cppcheck --error-exitcode=1 *.c
- make
- make test
- restructuredtext-lint --encoding=UTF-8 README
# vim:ts=2 sts=2 sw=2 et
<file_sep>/Makefile
# Copyright © 2017-2018 <NAME> <<EMAIL>>
# SPDX-License-Identifier: MIT
INSTALL = install
CFLAGS ?= -O2 -g
CFLAGS += -Wall -Wextra
ifneq "$(filter Linux GNU%,$(shell uname))" ""
LDLIBS += -ldl
endif
PREFIX = /usr/local
DESTDIR =
libdir = $(PREFIX)/lib
.PHONY: all
all: libgetenvy.so
.PHONY: install
install: libgetenvy.so
install -d $(DESTDIR)$(libdir)
install -m 644 $(<) $(DESTDIR)$(libdir)/$(<)
.PHONY: clean
clean:
rm -f *.so
lib%.so: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -shared -fPIC $(<) $(LDLIBS) -o $(@)
.PHONY: test
test: libgetenvy.so
LD_PRELOAD=./$(<) GETENVY=1 ls 2>&1 >/dev/null | grep -w getenv
.PHONY: test-installed
test-installed:
LD_PRELOAD=libgetenvy.so GETENVY=1 ls 2>&1 >/dev/null | grep -w getenv
.error = GNU make is required
# vim:ts=4 sts=4 sw=4 noet
|
cd7746217b0fb2511e98f920402263a1cc3896bc
|
[
"Makefile",
"YAML"
] | 2 |
Makefile
|
punkeel/getenvy
|
c9fa689788529daadf6cfa4ca4df960232f660e2
|
1e2a2f05d4d10fc0a38fb35fbdfde5f65f92c776
|
refs/heads/master
|
<file_sep># API
First create a camera instance:
* `camera = GoProHero([ip, password, loglevel])` - initialize a camera object
Then, the follow methods are available on the camera instance:
* `password(password)` - get or set the password of a camera object
* `status()` - get status packets and translate them
* `image()` - get an image and return it as a base64-encoded PNG string
* `command(param, value)` - send one of the supported commands
* `test(url)` - a simple testing interface to try out HTTP requests
The following class methods are also available:
* `@classmethod config()` - returns a dictionary with the current configuration
## Commands
These commands are used for both `camera.command()` and the `goproctl` command line interface.
Parameter | Values
--- |:---
power | `sleep`, `on`
record | `off`, `on`
preview | `off`, `on`
orientation | `up`, `down`
mode | `video`, `still`, `burst`, `timelapse`, `timer`, `hdmi`
volume | `0`, `70`, `100`
locate | `off`, `on`
|
571dfc984fa2a492a7a1321d94329a5b9cc4088e
|
[
"Markdown"
] | 1 |
Markdown
|
tpanzarella/goprohero
|
e61b3265dcd0644a9fffab79d4b17da7b18210c2
|
596d990e1ff711f0b2df5a3be2d390c6622c5fb8
|
refs/heads/master
|
<repo_name>zrx318/my_algorithm_practice<file_sep>/src/main/java/com/rongxin/tooffer/_Solution57.java
package com.rongxin.tooffer;
/**
* @ClassName _Solution57
* @Author RX_Zhao
* <p>
* 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
* 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
**/
public class _Solution57 {
public TreeLinkNode GetNext(TreeLinkNode node) {
if (node == null) {
return null;
}
//先判断右节点
if (node.right != null) {
node = node.right;
while (node.left != null) {
node = node.left;
}
return node;
}
//右节点没值,判断父节点的左右节点?
if (node.next != null && node == node.next.right) { //右儿子
node = node.next;
while (node != null && node.next != null && node.next.right == node) {
node = node.next;
}
}
if (node.next != null){
return node.next;
}
return null;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution64.java
package com.rongxin.tooffer;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* 给定一个数组和滑动窗口的大小,
* 找出所有滑动窗口里数值的最大值。
* 例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,
* 那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};
* 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个:
* {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
*/
public class Solution64 {
public ArrayList<Integer> maxInWindows(int[] num, int size) {
return null;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/__Solution56.java
package com.rongxin.tooffer;
/**
* @ClassName __Solution56
* @Author RX_Zhao
* <p>
* 题目描述
* 在一个排序的链表中,存在重复的结点,
* 请删除该链表中重复的结点,重
* 复的结点不保留,返回链表头指针。
* 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
**/
public class __Solution56 {
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null){
return pHead;
}
if (pHead.val != pHead.next.val){
pHead.next = deleteDuplication(pHead.next);
return pHead;
}else {
ListNode head = pHead.next;
while (head != null && head.val == pHead.val){
head = head.next;
}
return deleteDuplication(head);
}
}
}
<file_sep>/src/main/java/com/rongxin/sort/QuickSortDemo.java
package com.rongxin.sort;
import java.util.Arrays;
/**
* @ClassName QuickSortDemo
* @Author RX_Zhao
* @Date 16:07
**/
public class QuickSortDemo {
public static void main(String[] args) {
int[] arr = {3, 2, 4, 6, 5, 7, 8, 1, 0, 9};
QuickSortDemo quickSortDemo = new QuickSortDemo();
quickSortDemo.quickSort(arr, 0, arr.length - 1);
System.out.printf(Arrays.toString(arr));
}
private void quickSort(int[] arr, int left, int right) {
int begin = left;
int end = right;
int mid = begin + (end - begin) / 2;
int value = arr[mid];
while (begin < end) {
if (arr[begin] < value) {
begin++;
}
if (arr[end] > value) {
end--;
}
if (arr[begin] >= value && arr[end] <= value) {
int temp = arr[begin];
arr[begin] = arr[end];
arr[end] = temp;
begin++;
end--;
}
}
if (end > left) {
quickSort(arr, left, end);
}
if (begin < right) {
quickSort(arr, begin, right);
}
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution16.java
package com.rongxin.tooffer;
/**
* 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
*/
public class Solution16 {
//遍历方式
public ListNode Merge1(ListNode list1, ListNode list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
ListNode node = list1.val <= list2.val ? list1 : list2;
if (node == list1) {
list1 = list1.next;
} else {
list2 = list2.next;
}
ListNode temp = node;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
temp.next = list1;
list1 = list1.next;
temp = temp.next;
} else {
temp.next = list2;
list2 = list2.next;
temp = temp.next;
}
}
while (list1 != null) {
temp.next = list1;
list1 = list1.next;
temp = temp.next;
}
while (list2!= null) {
temp.next = list2;
list2 = list2.next;
temp = temp.next;
}
return node;
}
//递归方式
public ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
ListNode node;
if (list1.val <= list2.val) {
list1.next = Merge(list1.next, list2);
return list1;
} else {
list2.next = Merge(list1, list2.next);
return list2;
}
}
}
<file_sep>/README.md
# 算法练习专题
## [剑指offer](./src/main/java/com/rongxin/tooffer)
完结,撒花 ✿✿ヽ(°▽°)ノ✿
## [排序算法](./src/main/java/com/rongxin/sort)
[冒泡排序](./src/main/java/com/rongxin/sort/BubbleSortDemo.java)
[选择排序](./src/main/java/com/rongxin/sort/ChoiceSortDemo.java)
[快速排序](./src/main/java/com/rongxin/sort/QuickSortDemo.java)
[归并排序](./src/main/java/com/rongxin/sort/MergeSortDemo.java)
[堆 排 序](./src/main/java/com/rongxin/sort/HeapSortDemo.java)
[希尔排序](./src/main/java/com/rongxin/sort/XierSortDemo.java)
## 重要算法
1. [LRU](./src/main/java/com/rongxin/extra/KVCache.java)
- [LRU-my](./src/main/java/com/rongxin/extra/LRUCache.java)<file_sep>/src/main/java/com/rongxin/tooffer/Solution07.java
package com.rongxin.tooffer;
/**
* 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。
* n<=39
*
**/
public class Solution07 {
public int Fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int[] fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution35.java
package com.rongxin.tooffer;
/**
* 题目描述
* 在数组中的两个数字,如果前面一个数字大于后面的数字,
* 则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。
* 并将P对1000000007取模的结果输出。 即输出P%1000000007
* 输入描述:
* 题目保证输入的数组中没有的相同的数字
* <p>
* 数据范围:
* <p>
* 对于%50的数据,size<=10^4
* <p>
* 对于%75的数据,size<=10^5
* <p>
* 对于%100的数据,size<=2*10^5
*/
public class Solution35 {
int num;
public int InversePairs(int[] array) {
mergeSort(array);
return num;
}
private void mergeSort(int[] arr) {
mergeSort(arr, 0, arr.length - 1);
}
private void mergeSort(int[] arr, int left, int right) {
int mid = left + (right - left) / 2;
if (left < right) {
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right, new int[right - left + 1]);
}
}
private void merge(int[] arr, int left, int mid, int right, int[] temp) {
int t = 0;
int l = left;
int r = mid + 1;
while (l <= mid && r <= right) {
if (arr[l] <= arr[r]) {
temp[t++] = arr[l++];
} else {
num = num + mid - l + 1;
num %= 1000000007;
temp[t++] = arr[r++];
}
}
while (l <= mid) {
temp[t++] = arr[l++];
}
while (r <= right) {
temp[t++] = arr[r++];
}
t = 0;
while (left <= right) {
arr[left++] = temp[t++];
}
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution43.java
package com.rongxin.tooffer;
/**
* 汇编语言中有一种移位指令叫做循环左移(ROL),
* 现在有个简单的任务,就是用字符串模拟这个指令的运算结果。
* 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。
* 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
*/
public class Solution43 {
public static void main(String[] args) {
Solution43 solution43 = new Solution43();
String abcXYZdef = solution43.LeftRotateString("abcXYZdef", 0);
System.out.println(abcXYZdef);
}
public String LeftRotateString(String str, int n) {
if (str == null || "".equals(str)) {
return str;
}
int x = n % str.length();
System.out.println(x);
return str.substring(x) + str.substring(0, x);
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution49.java
package com.rongxin.tooffer;
/**
* @ClassName Solution49
* @Author RX_Zhao
* <p>
* 将一个字符串转换成一个整数,
* 要求不能使用字符串转换整数的库函数。
* 数值为0或者字符串不是一个合法的数值则返回0
**/
public class Solution49 {
public int StrToInt(String str) {
return -1;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution51.java
package com.rongxin.tooffer;
/**
* @ClassName Solution51
* @Author RX_Zhao
* @Date 15:33
* @Version 给定一个数组A[0, 1, ..., n-1],
* 请构建一个数组B[0,1,...,n-1],
* 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。
* 不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)
* <p>
* 解:
* B1[0] = 1
* B1[1] = A[0]
* B1[2] = A[0] * A[1]
* ...
* B1[n-1] = A[0] * A[1] * ... * A[n -2];
* <p>
* B2[0] = 1
* B2[1] = A[n-1]
* ...
* B2[n-1] = A[n-1] * A[n-2] * ... * A[1]
**/
public class Solution51 {
public int[] multiply(int[] A) {
int[] B = new int[A.length];
int[] B1 = new int[A.length]; //从左到右
int[] B2 = new int[A.length]; //从右到左
for (int i = 0; i < A.length; i++) {
if (i == 0) {
B1[0] = 1;
B2[0] = 1;
continue;
}
B1[i] = B1[i - 1] * A[i - 1];
B2[i] = B2[i - 1] * A[A.length - i];
}
for (int i = 0; i < A.length; i++) {
B[i] = B1[i] * B2[A.length - i - 1];
}
return B;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution32.java
package com.rongxin.tooffer;
/**
* 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,
* 打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},
* 则打印出这三个数字能排成的最小数字为321323。
*/
public class Solution32 {
String min;
public String PrintMinNumber(int[] numbers) {
dfs(numbers, 0, new StringBuffer(), new boolean[numbers.length]);
return min;
}
private void dfs(int[] num, int index, StringBuffer sb, boolean[] flag) {
if (index == num.length) {
min = getMin(min, sb.toString());
return;
}
for (int i = 0; i < num.length; i++) {
if (!flag[i]) {
flag[i] = true;
sb.append(num[i]);
dfs(num, index + 1, new StringBuffer(sb), flag);
flag[i] = false;
sb.delete(sb.length() - String.valueOf(num[i]).length(), sb.length());
}
}
}
private static String getMin(String min, String str) {
if (min == null) {
return str;
}
if (min.length() < str.length()) {
return min;
} else if (min.length() > str.length()) {
return str;
} else {
for (int i = 0; i < min.length(); i++) {
if (min.charAt(i) < str.charAt(i)) {
return min;
} else if (min.charAt(i) > str.charAt(i)) {
return str;
} else {
continue;
}
}
}
return min;
}
}
<file_sep>/src/main/java/com/rongxin/extra/KVCache.java
package com.rongxin.extra;
class KVCache<K, V> {
Node head = new Node();
Node tail;
int max;
int size = 0;
public KVCache(int n) {
max = n;
tail = head;
}
public void put(K key, V value) {
Node temp = get(key);
if (temp != null) {
temp.value = value;
} else {
size++;
tail.next = new Node(key, value);
tail = tail.next;
if (size > max) {
size--;
if (size != 0) {
head.next = head.next.next;
}
}
}
}
public void delete(V key) {
Node pre = head;
Node cur = head.next;
while (cur != null) {
if (key.equals(cur.key)) {
pre.next = cur.next;
size--;
break;
}
}
pre = cur;
cur = cur.next;
}
public Node get(K key) {
Node cur = head;
while (cur != null) {
if (key.equals(cur.key)) {
return cur;
}
cur = cur.next;
}
return null;
}
class Node<K, V> {
K key;
V value;
Node next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
public Node() {
this.key = (K) new Object();
this.value = (V) new Object();
}
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution17.java
package com.rongxin.tooffer;
/**
* 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
*/
public class Solution17 {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
if (root2 == null || root1 == null) return false;
return isSon(root1, root2) || HasSubtree(root1.left,root2) || HasSubtree(root1.right, root2);
}
private boolean isSon(TreeNode root, TreeNode root2) {
if (root2 == null) return true;
if (root == null ) return false;
if (root.val != root2.val) return false;
return isSon(root.left, root2.left) && isSon(root.right, root2.right);
}
}
<file_sep>/src/main/java/com/rongxin/sort/BubbleSortDemo.java
package com.rongxin.sort;
import java.util.Arrays;
/**
**/
public class BubbleSortDemo {
public static void main(String[] args) {
int[] arr = {3,2,4,6,5,7,8,1,0,9};
BubbleSortDemo bubbleSortDemo = new BubbleSortDemo();
bubbleSortDemo.bubbleSort(arr);
System.out.printf(Arrays.toString(arr));
}
private void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < i; j++) {
boolean flag = false;
if (arr[i] < arr[j]) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
flag = true;
}
if (!flag) {
break;
}
}
}
}
}
<file_sep>/src/main/java/com/rongxin/sort/MergeSortDemo.java
package com.rongxin.sort;
import java.util.Arrays;
/**
* 归并排序
*/
public class MergeSortDemo {
public static void main(String[] args) {
int[] arr = {1, 3, 2, 6, 5, 0, 9, 6, 8, 7};
new MergeSortDemo().mergeSort(arr);
System.out.println(Arrays.toString(arr));
}
private void mergeSort(int[] arr) {
mergeSort(arr, 0, arr.length - 1);
}
private void mergeSort(int[] arr, int left, int right) {
int mid = left + (right - left) / 2;
if (left < right) {
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right, new int[right - left + 1]);
}
}
private void merge(int[] arr, int left, int mid, int right, int[] temp) {
int t = 0;
int l = left;
int r = mid + 1;
while (l <= mid && r <= right) {
if (arr[l] <= arr[r]) {
temp[t++] = arr[l++];
} else {
temp[t++] = arr[r++];
}
}
while (l <= mid) {
temp[t++] = arr[l++];
}
while (r <= right) {
temp[t++] = arr[r++];
}
t = 0;
while (left <= right) {
arr[left++] = temp[t++];
}
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution58.java
package com.rongxin.tooffer;
/**
* @ClassName Solution58
* @Author RX_Zhao
*
* 题目描述
* 请实现一个函数,用来判断一棵二叉树是不是对称的。
* 注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
*
**/
public class Solution58 {
boolean isSymmetrical(TreeNode pRoot) {
if (pRoot == null){
return true;
}
return isSymmetrical(pRoot.left,pRoot.right);
}
private boolean isSymmetrical(TreeNode left, TreeNode right) {
if (left == null && right == null){
return true;
}
if (left == null || right == null){
return false;
}
if (left.val == right.val){
return isSymmetrical(left.left,right.right) && isSymmetrical(left.right,right.left);
}
return false;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution37.java
package com.rongxin.tooffer;
/**
* 题目描述
* 统计一个数字在排序数组中出现的次数。
*/
public class Solution37 {
public static void main(String[] args) {
int[] arr = {3, 3, 3, 3, 4, 5};
int k = 3;
Solution37 solution37 = new Solution37();
int i = solution37.GetNumberOfK(arr, k);
System.out.println(i);
}
public int GetNumberOfK(int[] array, int k) {
if (array == null || array.length == 0) {
return 0;
}
int left = getIndex(array, true, k);
int right = getIndex(array, false, k);
if (left == -1 || right == -1) {
return 0;
}
return right - left + 1;
}
private int getIndex(int[] array, boolean left, int k) {
int begin = 0;
int end = array.length - 1;
int mid;
while (begin <= end) {
mid = begin + (end - begin) / 2;
if (array[mid] < k) {
begin = mid + 1;
} else if (array[mid] > k) {
end = mid - 1;
} else {
if (left) {
if (mid > begin && array[mid - 1] == k) {
end = mid - 1;
} else {
return mid;
}
} else {
if (mid < end && array[mid + 1] == k) {
begin = mid + 1;
} else {
return mid;
}
}
}
}
return -1;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution04.java
package com.rongxin.tooffer;
import java.util.Arrays;
/**
* 输入某二叉树的前序遍历和中序遍历的结果,
* 请重建出该二叉树。
* 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
*/
public class Solution04 {
/**
* 采用递归方式,假设现在就是最后一个节点了,我如何处理,left? right?
*/
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre == null || pre.length == 0) return null;
if (pre.length > 1) {
int findIndex = 0;
for (int i = 0; i < pre.length; i++) {
if (pre[0] == in[i]) {
findIndex = i;
break;
}
}
int[] pre1 = Arrays.copyOfRange(pre,1, findIndex + 1);
int[] pre2 = Arrays.copyOfRange(pre, findIndex + 1, pre.length);
int[] in1 = Arrays.copyOfRange(in,0, findIndex);
int[] in2 = Arrays.copyOfRange(in,findIndex + 1, in.length);
TreeNode root = new TreeNode(pre[0]);
root.left = reConstructBinaryTree(pre1, in1);
root.right = reConstructBinaryTree(pre2, in2);
return root;
} else {
return new TreeNode(pre[0]);
}
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution33.java
package com.rongxin.tooffer;
/**
* 把只包含质因子2、3和5的数称作丑数(Ugly Number)。
* 例如6、8都是丑数,但14不是,因为它包含质因子7。 习
* 惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
*/
public class Solution33 {
public int GetUglyNumber_Solution(int index) {
int[] ugly = new int[index];
ugly[0] = 1;
int p2 = 0, p3 = 0, p5 = 0;
for (int i = 1; i < ugly.length; i++) {
ugly[i] = min(2 * ugly[p2], 3 * ugly[p3], 5 * ugly[p5]);
if (ugly[i] == 2 * ugly[p2]) {
p2++;
}
if (ugly[i] == 3 * ugly[p3]) {
p3++;
}
if (ugly[i] == 5 * ugly[p5]) {
p5++;
}
}
return ugly[index - 1];
}
private int min(int i, int i1, int i2) {
int min = i;
min = min < i1 ? min : i1;
min = min < i2 ? min : i2;
return min;
}
}
<file_sep>/src/main/java/com/rongxin/sort/ChoiceSortDemo.java
package com.rongxin.sort;
/**
* @ClassName ChoiceSortDemo
* @Author RX_Zhao
* @Date 16:38
*
*
**/
public class ChoiceSortDemo {
private static void choiceSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int min = arr[i];
int index = i;
for (int j = i; j < arr.length; j++) {
if (arr[j] <= min) {
index = j;
min = arr[j];
}
}
swap(arr, index, i);
}
}
private static void swap(int[] arr, int j, int i) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution65.java
package com.rongxin.tooffer;
/**
* 题目描述
* 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
* 路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
* 如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如:
* [a b c e
* s f c s
* a d e e]
* 矩阵中包含一条字符串"bcced"的路径,
* 但是矩阵中不包含"abcb"路径,
* 因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,
* 路径不能再次进入该格子。
*/
public class Solution65 {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
return false;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution67.java
package com.rongxin.tooffer;
import java.util.Arrays;
/**
* 题目描述
* 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),
* 每段绳子的长度记为k[1],...,k[m]。请问k[1]x...xk[m]可能的最大乘积是多少?
* 例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
* <p>
* <p>
* 输入描述:
* 输入一个数n,意义见题面。(2 <= n <= 60)
* 输出描述:
* 输出答案。
*/
public class Solution67 {
public static void main(String[] args) {
Solution67 s = new Solution67();
int i = s.cutRope(15);
System.out.println(i);
}
public int cutRope(int target) {
if (target <= 2) {
return 1;
}
if (target == 3){
return 2;
}
int[] dp = new int[target + 1];
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
for (int i = 4; i <= target; i++) {
int max = 0;
for (int j = 1; j <= i -1 ; j++) {
max = Math.max(dp[j]*dp[i-j],max);
}
dp[i] = max;
}
return dp[target];
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution24.java
package com.rongxin.tooffer;
import java.util.ArrayList;
/**
* @ClassName Solution24
* @Author RX_Zhao
* @Date 14:36
* <p>
* 输入一颗二叉树的根节点和一个整数,
* 按字典序打印出二叉树中结点值的和为输入整数的所有路径。
* 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
**/
public class Solution24 {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
dfs(root, target, new ArrayList<Integer>());
return res;
}
private void dfs(TreeNode root, int target, ArrayList<Integer> list) {
if (root == null && target == 0) {
if (!res.contains(list) && !list.isEmpty()){
res.add(list);
}
return;
}
if (root == null || target <= 0) return;
list.add(root.val);
dfs(root.left, target - root.val, new ArrayList<>(list));
dfs(root.right, target - root.val, new ArrayList<>(list));
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution42.java
package com.rongxin.tooffer;
import java.util.ArrayList;
/**
* 输入一个递增排序的数组和一个数字S,
* 在数组中查找两个数,使得他们的和正好是S,
* 如果有多对数字的和等于S,输出两个数的乘积最小的。
* <p>
* 输出描述:
* 对应每个测试案例,输出两个数,小的先输出。
*/
public class Solution42 {
public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) {
ArrayList<Integer> list = new ArrayList<>();
if (array == null || array.length == 0) {
return list;
}
int left = 0;
int right = array.length - 1;
while (left < right) {
int v = array[left] + array[right];
if (v == sum) {
if (list.isEmpty()) {
list.add(array[left]);
list.add(array[right]);
} else {
if (list.indexOf(0) * list.indexOf(1) > array[left] * array[right]) {
list.add(0, array[left]);
list.add(1, array[right]);
}
}
left++;
} else if (v < sum) {
left++;
} else {
right--;
}
}
return list;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution44.java
package com.rongxin.tooffer;
/**
* @ClassName Solution44
* @Author RX_Zhao
* @Date 13:55
* @Version
**/
/**
* 牛客最近来了一个新员工Fish,
* 每天早晨总是会拿着一本英文杂志,
* 写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,
* 有一天他向Fish借来翻看,但却读不懂它的意思。
* 例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正
* 确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
*/
public class Solution44 {
public String ReverseSentence(String str) {
char[] charStr = str.toCharArray();
for (int i = 0; i < charStr.length / 2; i++) {
char temp = charStr[i];
charStr[i] = charStr[charStr.length - 1 - i];
charStr[charStr.length - i - 1] = temp;
}
int start = 0;
int end;
for (int i = 0; i < charStr.length; i++) {
if (charStr[i] == ' ' || i == charStr.length - 1) {
if (charStr[i] == ' ') {
end = i;
} else {
end = i + 1;
}
for (int j = start; j < (end + start) / 2; j++) {
char temp = charStr[j];
charStr[j] = charStr[end - 1 + start - j];
charStr[end - 1 + start - j] = temp;
}
start = end + 1;
}
}
return String.valueOf(charStr);
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/_Solution06.java
package com.rongxin.tooffer;
/**
* 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
**/
public class _Solution06 {
public int minNumberInRotateArray(int [] array) {
if (array == null || array.length == 0) return 0;
int left = 0;
int right = array.length - 1;
int mid;
while(left < right) {
if (array[left] < array[right]) return array[left];
mid = left + (right - left) / 2;
if (array[left] < array[mid]) {
left = mid + 1;
} else if (array[left] > array[mid]) {
right = mid;
} else {
left ++;
}
}
return array[right];
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/Solution39.java
package com.rongxin.tooffer;
/**
* 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
* <p>
* 在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
*/
public class Solution39 {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
return Math.abs(TreeDepth(root.left) - TreeDepth(root.right)) <= 1;
}
//题38中的求深度
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
}
<file_sep>/src/main/java/com/rongxin/tooffer/_Solution61.java
package com.rongxin.tooffer;
/**
*
* 序列化二叉树
*
* 题目描述
* 请实现两个函数,分别用来序列化和反序列化二叉树
*
* 二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,
* 从而使得内存中建立起来的二叉树可以持久保存。
* 序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,
* 序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。
*
* 二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
*
* 例如,我们可以把一个只有根节点为1的二叉树序列化为"1,",然后通过自己的函数来解析回这个二叉树
*/
public class _Solution61 {
String Serialize(TreeNode root) {
if (root == null) {
return "#!";
}
return root.val+"!"+Serialize(root.left) + Serialize(root.right);
}
int index = -1;
TreeNode Deserialize(String str) {
index++;
String[] split = str.split("!");
if (index >= split.length){
return null;
}
TreeNode tree = null;
if (!split[index].equals("#")){
tree = new TreeNode(Integer.valueOf(split[index]));
tree.left = Deserialize(str);
tree.right = Deserialize(str);
}
return tree;
}
}
|
a8b3067193046308cfc8ee4584bed057e7897e8e
|
[
"Java",
"Markdown"
] | 29 |
Java
|
zrx318/my_algorithm_practice
|
0c01c7253b2f3708527f110daf272f49021941c5
|
0e283b539cb70fb6a21fe2f0bcef3c202d29f0ee
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { IMajor } from 'src/app/interfaces/major.interface';
import { IUser } from 'src/app/interfaces/user.interface';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';
@Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
user: IUser;
preskills: string;
skills: string[]
majors: IMajor[] = [{
name: 'Computer Engineering',
abrv: 'CPE'
},
{
name: 'Computer Science',
abrv: 'CS'
},
{
name: 'Mechanical Engineering',
abrv: 'ME'
}];
constructor(private http: HttpClient, private router: Router, public storage: Storage) {
this.user = {
firstname: null,
lastname: null,
email: null,
phonenum: null,
major: null,
position: {
internship: false,
coop: false,
fulltime: false
},
citizenship: null,
linelocation: null,
skills: null
};
}
ngOnInit() {
}
splitSkills() {
this.skills = this.preskills.split(',');
this.user.skills = this.skills;
}
register() {
console.log('making acct');
this.splitSkills();
let ip = 'http://172.16.31.10';
let url = `${ip}/api/students`;
let headers = new HttpHeaders().set('Content-Type', 'application/JSON');
this.storage.set('current_user', this.user);
this.http.post<boolean>(url, this.user, { headers }).subscribe(res => {
console.log(`#########################################`);
console.log(`Server Returned: `);
console.log(res);
this.router.navigateByUrl('/map');
}, err => {
console.log(err);
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Storage } from '@ionic/storage';
import { IUser } from 'src/app/interfaces/user.interface';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
email: string;
password: string;
badLogin: boolean;
constructor(private http: HttpClient, private router: Router, public storage: Storage) {
//this.badLogin = false;
}
ngOnInit() {
}
login() {
console.log(`The email is: ${this.email}`);
console.log(`Trying with password: ${this.password}`);
let ip = 'http://172.16.31.10'
let url = `${ip}/api/auth`;
let headers = new HttpHeaders().set('Content-Type', 'application/JSON');
this.http.post<IUser>(url, { 'email': this.email }, { headers }).subscribe(res => {
console.log(`#########################################`);
console.log(`Server Returned: `);
this.storage.set('current_user', res);
this.storage.get('current_user').then(res => {
if (res.email) {
console.log(res);
this.router.navigateByUrl('/map');
}
else
this.badLogin = true;
});
});
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
import { ICompany } from 'src/app/interfaces/company.interface';
import { ModalController } from '@ionic/angular';
import { Storage } from '@ionic/storage';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { IUser } from 'src/app/interfaces/user.interface';
@Component({
selector: 'app-company-detail',
templateUrl: './company-detail.page.html',
styleUrls: ['./company-detail.page.scss'],
})
export class CompanyDetailPage implements OnInit {
@Input() company: ICompany;
queueSize: number;
curUser: IUser;
enqueued: boolean;
ip: string = 'http://34.69.192.84';
headers: HttpHeaders = new HttpHeaders().set('Content-Type', 'application/JSON');
constructor(private mctrl: ModalController, private http: HttpClient, public storage: Storage) {
this.storage.get('current_user').then(res => {
this.curUser = res;
console.log(res);
});
}
ngOnInit() {
let url = `${this.ip}/api/size`;
this.http.post<any>(url, { company: this.company.name }, { headers: this.headers }).subscribe(res => {
this.queueSize = res.size;
});
}
closeCard() {
this.mctrl.dismiss({
'dismissed': true
});
}
joinQueue() {
console.log(`joining queue for ${this.company.name}`);
let url = `${this.ip}/api/enqueue`;
this.http.post<any>(url, {
student: this.curUser.email,
company: this.company.name
},
{ headers: this.headers }).subscribe(res => {
this.enqueued = res.success;
this.closeCard();
});
}
leaveQueue() {
console.log(`Leaving ${this.company.name}'s queue`);
let url = `${this.ip}/api/dequeue-student`;
this.http.post<any>(url, {
student: this.curUser.email,
company: this.company.name
}).subscribe(res => {
console.log(`Server said: ${res.success}`);
this.closeCard();
});
}
}
<file_sep>.COE {
display: inline-block;
width: 33%;
}<file_sep>export interface IMajor {
name: string;
abrv: string;
}<file_sep>import { IMajor } from './major.interface';
interface IPosition {
internship: boolean,
coop: boolean,
fulltime: boolean
}
export interface IUser {
firstname: string,
lastname: string,
email: string,
phonenum: number,
major: IMajor,
position: IPosition,
citizenship: string,
linelocation: number,
skills: string[];
}<file_sep>export interface ICompany {
name: string,
description: string,
link: string,
logourl: string,
job: string,
major: string
}<file_sep># Ram Hacks 2019 Frontend
## <NAME>, <NAME>, <NAME>, <NAME>
<file_sep>import { Component, OnInit } from '@angular/core';
import { ICompany } from 'src/app/interfaces/company.interface';
import { IUser } from 'src/app/interfaces/user.interface';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ModalController } from '@ionic/angular';
import { CompanyDetailPage } from '../company-detail/company-detail.page';
import { Storage } from '@ionic/storage';
@Component({
selector: 'app-map',
templateUrl: './map.page.html',
styleUrls: ['./map.page.scss'],
})
export class MapPage implements OnInit {
companies1: ICompany[];
companies2: ICompany[];
companies3: ICompany[];
constructor(private http: HttpClient, private mctrl: ModalController, public storage: Storage) { }
ngOnInit() {
this.getCompanies();
}
getCompanies() {
console.log(`Making a call to get list of comapies`);
let ip = 'http://172.16.17.32'
let url = `${ip}/api/company`;
this.http.get<ICompany[]>(url).subscribe(res => {
console.log(`#########################################`);
console.log(`Server Returned a list of size: ${res.length} `);
console.log(res);
this.companies1 = res.slice(0, Math.ceil(res.length / 3));
console.log(`C1: ${this.companies1.length}`);
this.companies2 = res.slice(Math.ceil(res.length / 3), Math.ceil(res.length / 3) * 2);
console.log(`C2: ${this.companies2.length}`);
this.companies3 = res.slice(Math.ceil(res.length / 3) * 2, res.length);
console.log(`C3: ${this.companies3.length}`);
});
}
async openCompanyDetail(company: ICompany) {
let curUser: IUser;
this.storage.get('current_user').then(res => {
curUser = res;
let ip = 'http://172.16.17.32'
let url = `${ip}/api/status`;
let headers = new HttpHeaders().set('Content-Type', 'application/JSON');
this.http.post<any>(url, { company: company.name, student: curUser.email }, { headers }).subscribe(async res => {
curUser.linelocation = res.pos;
this.storage.set('current_user', curUser);
console.log(res);
console.log(curUser);
let detailMod = await this.mctrl.create({
component: CompanyDetailPage,
componentProps: { 'company': company }
});
return await detailMod.present();
});
})
}
}
|
b46f25eb38acf7e148e26fb6c2334fd096168054
|
[
"SCSS",
"Markdown",
"TypeScript"
] | 9 |
SCSS
|
gldnbxy/ramhacks19_frontend
|
dc2ad29e91ab30a2f408857898c7e18bd0510171
|
0cc0cea824ca75ffaf322be19312775bb656b4cc
|
refs/heads/master
|
<repo_name>alg/coliseum<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.0.rc2'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.0'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'haml-rails'
gem 'rdiscount'
gem 'capistrano'
gem 'twitter-bootstrap-rails', :git => 'http://github.com/seyhunak/twitter-bootstrap-rails.git'
group :test do
# Pretty printed test output
gem 'turn', '~> 0.8.3', :require => false
gem 'rspec'
gem 'rspec-rails'
gem 'mongoid-rspec'
gem 'faker'
gem 'timecop'
gem 'factory_girl_rails'
gem 'shoulda'
gem 'guard'
gem 'guard-rspec'
end
<file_sep>/app/assets/stylesheets/global.scss
body {
margin-top: 60px;
}
#search-field, #comment-field {
margin-bottom: 20px;
width: 450px;
}
#search-results {
tr {
cursor: pointer;
.time { width: 30px; }
}
}
#player {
display: none;
h3 {
overflow: hidden;
height: 4ex;
}
input {
width: 450px;
}
.comment {
padding: 5px;
margin: 5px 0;
}
}
<file_sep>/srv/src/wsserv.erl
-module(wsserv).
-compile(export_all).
-record(state, {ws, youtube_id}).
% start misultin http server
start() -> start(8080).
start(Port) ->
misultin:start_link([
{port, Port},
{name, ?MODULE},
{loop, fun(_) -> ok end},
{ws_loop, fun(Ws) -> handle_websocket(Ws) end}]).
% stop misultin
stop() ->
misultin:stop(?MODULE).
% callback on received websockets data
handle_websocket(Ws) ->
cmserv:register(),
loop(#state{ws = Ws}).
loop(S = #state{ws = Ws}) ->
receive
{browser, Data} ->
case parse_data(Data) of
{join, YoutubeId} ->
cmserv:subscribe(YoutubeId),
Response = lists:foldl(fun(X, Acc) -> Acc ++ "~" ++ X end, "comments", cmserv:comments(YoutubeId)),
Ws:send([Response]),
loop(S#state{youtube_id = YoutubeId});
{comment, Body} ->
cmserv:comment(S#state.youtube_id, Body),
loop(S);
Unknown ->
io:format("Unknown request: ~p~n", [ Unknown ]),
loop(S)
end;
{comment, Body} ->
Ws:send(["comment~" ++ Body]),
loop(S);
_Ignore ->
loop(S)
end.
parse_data(Data) ->
[Command|Params] = re:split(Data, "~", [{return, list}]),
{list_to_existing_atom(Command), Params}.
<file_sep>/app/views/layouts/_header.html.erb
<div class="topbar">
<div class="fill">
<div class="container">
<%= link_to "Coliseum", :root, :class => 'brand' %>
<ul class="nav">
<li><%= link_to "Home", "#" %></li>
<li><%= link_to "Explore", "#" %></li>
</ul>
</div>
</div>
</div>
<file_sep>/doc/notes.md
Views
-----
* Use `Em.View` to link JS to a portion of HTML and provide necessary
bindings for data and handle any events (clicks, key presses etc).
* Do not perform any business logic in the views, but call appropriate
controllers instead.
Controllers
-----------
* Use for handling operations with data.
* Controllers don't access views, but only models. Views bind to
controllers and observe their property changes instead.
View Templates
--------------
* If a Handlebar template has a name, it won't be rendered into the page
upon load.
* To link a template to a certain JS view, define a view like this:
* details_view.js
App.MyView = Em.View.extend({
templateName: 'details-view',
firstName: 'Mark'
});
* index.html
<div class='data'>
{{view App.MyView}}
</div>
...
<script type="text/x-handlebars" data-template-name="details-view">
{{firstName}}
</script>
<file_sep>/app/assets/javascripts/utils.js
function seconds_to_time(seconds) {
var hrs = Math.floor(seconds / 3600),
rem = seconds - hrs * 3600,
min = Math.floor(rem / 60),
sec = rem % 60;
return "" + (hrs > 0 ? hrs + ":" : "") +
(min < 10 ? "0" : "") + min + ":" +
(sec < 10 ? "0" : "") + sec;
}
<file_sep>/app/assets/javascripts/search.js
/* Search bar component. */
Coliseum.SearchBar = Em.TextField.extend({
valueBinding: 'Coliseum.searchResultsController.query',
insertNewline: function() {
Coliseum.searchResultsController.search();
}
});
/* Search results. */
Coliseum.searchResultsController = Em.ArrayController.create({
// list of found videos
content: [],
// current query
query: null,
// current page
page: 1,
// items per search page
perPage: 15,
// TRUE when search is in progress
isSearching: false,
/* Refresh the contents by searching for the 'query'. */
search: function() {
var self = this, query = this.get('query');
// hide results
this.set('content', []);
if (query != null && query.length > 0) {
// set the searching status
this.set('isSearching', true);
var c = $.getJSON('http://gdata.youtube.com/feeds/api/videos?alt=json',
{ q: query, 'max-results': this.get('perPage'), v: 2 });
// populate results
c.success(function(data) {
var entries = data.feed.entry, results = [];
for (var i = 0; i < entries.length; i++) {
var v = Coliseum.FoundVideo.fromYoutube(entries[i]);
console.log(v.get('youtubeId'));
results.push(v);
}
self.set('content', results);
});
// reset the searching status
c.complete(function() {
self.set('isSearching', false);
});
}
}
});
/* Search view */
Coliseum.SearchView = Em.View.extend({
templateName: 'search-view',
resultsBinding: 'Coliseum.searchResultsController.content',
isSearchingBinding: 'Coliseum.searchResultsController.isSearching'
});
/* Single result item view. */
Coliseum.ResultView = Em.View.extend({
// this view video file
video: null,
click: function(evt) {
console.log('Clicked on: ', this.get('video').get('youtubeId'));
Coliseum.set('selectedVideo', this.get('video'));
},
videoChanged: function() {
console.log('yid: ' + this.get('video').get('youtubeId'));
}.observes('video')
});
<file_sep>/spec/support/mongoid.rb
RSpec.configure do |config|
# Cleanup database before each spec
config.before do
Mongoid.master.collections.select {|c| c.name !~ /system/ }.each(&:drop)
end
end
<file_sep>/app/views/layouts/_page_header.html.erb
<% if @page_title %>
<div class="page-header">
<h1>
<%= @page_title %>
<% if @page_tagline %>
<small><%= @page_tagline %></small>
<%- end -%>
</h1>
</div>
<% end %>
<file_sep>/app/assets/javascripts/app.js
Coliseum = Ember.Application.create({
// currently selected video
selectedVideo: null,
websocket: new WS(),
});
// Video that comes from Youtube -- not a DS object
Coliseum.FoundVideo = Em.Object.extend({
youtubeId: null,
title: null,
descr: null,
seconds: null,
length: function() {
return seconds_to_time(this.get('seconds'));
}.property('seconds'),
youtubeIdChange: function() {
console.log(this.get('title') + ' -> ' + this.get('youtubeId'));
}.observes('youtubeId')
});
Coliseum.FoundVideo.reopenClass({
fromYoutube: function(data) {
return Coliseum.FoundVideo.create({
youtubeId: data.id.$t.split(':')[3],
seconds: parseInt(data.media$group.yt$duration.seconds),
title: data.title.$t
});
}
});
// Comment object
Coliseum.Comment = Em.Object.extend({
body: null
});
<file_sep>/app/assets/javascripts/details.js
/* Detailed view of selected found video. */
Coliseum.DetailsView = Em.View.extend({
templateName: 'details-view',
videoBinding: 'Coliseum.selectedVideo',
titleBinding: 'video.title',
viewTitle: function() {
var t = this.get('title');
return t ? t : 'Watch video'
}.property('title'),
videoUrl: function() {
return "http://www.youtube.com/embed/" + this.getPath('.video.youtubeId');
}.property('video.youtubeId')
});
/* Comments for the video. */
Coliseum.videoCommentsController = Em.ArrayController.create({
// current comments list
content: [],
// current video Youtube Id
youtubeIdBinding: 'Coliseum*selectedVideo.youtubeId',
// TRUE if is currently loading
isLoading: false,
init: function() {
Coliseum.websocket.setListener(this);
},
onWebsocketCommand: function(cmd, args) {
if (cmd == "comments") {
this.set('content', []);
for (var i = 0; i < args.length; i++) {
this.pushObject(Coliseum.Comment.create({ body: args[i] }));
}
} else if (cmd == "comment") {
this.unshiftObject(Coliseum.Comment.create({ body: args[0] }));
}
console.log("command: ", cmd, args);
},
createComment: function(body) {
Coliseum.websocket.addComment(body);
},
// resets the comments and starts loading
youtubeIdChanged: function() {
var yid = this.get('youtubeId');
if (yid) Coliseum.websocket.join(yid);
}.observes('youtubeId')
});
/* Comment body field. */
Coliseum.CommentField = Em.TextField.extend({
disabled: true,
selectedVideoChanged: function() {
this.set('disabled', Coliseum.get('selectedVideo') == null);
}.observes('Coliseum.selectedVideo'),
insertNewline: function() {
Coliseum.videoCommentsController.createComment(this.get('value'));
this.set('value', null);
}
});
<file_sep>/spec/controllers/pages_controller_spec.rb
require 'spec_helper'
describe PagesController do
describe 'front' do
before { get :front }
it { should render_template :front }
end
end
<file_sep>/srv/src/cmserv.erl
-module(cmserv).
-compile(export_all).
-record(state, {videos, %% orddict: youtubeid - [ pid, pid2 ]
clients, %% orddict: pid - youtubeid
comments}). %% orddict: youtubeid -> [ comments ]
start() ->
erlang:register(?MODULE, Pid = spawn(?MODULE, init, [])),
Pid.
stop() ->
?MODULE ! shutdown.
register() ->
?MODULE ! {self(), register}.
subscribe(YoutubeId) ->
?MODULE ! {self(), {subscribe, YoutubeId}}.
comment(YoutubeId, Body) ->
?MODULE ! {self(), {comment, YoutubeId, Body}}.
comments(YoutubeId) ->
?MODULE ! {self(), {comments, YoutubeId}},
receive
{ok, List} -> List
end.
code_change() ->
?MODULE ! upgrade.
init() ->
loop(#state{videos = orddict:new(), clients = orddict:new(), comments = orddict:new()}).
loop(S = #state{}) ->
%io:format("Clients: ~p~n Videos: ~p~n", [ S#state.clients, S#state.videos ]),
receive
{Pid, register} ->
erlang:monitor(process, Pid),
loop(S);
{Pid, {subscribe, YoutubeId}} ->
NewVideos1 = unsubscribe(Pid, S#state.clients, S#state.videos),
% Subscribe
ClientPids = case orddict:find(YoutubeId, NewVideos1) of
{ok, Pids} -> Pids;
error -> []
end,
NewVideos = orddict:store(YoutubeId, [Pid|ClientPids], NewVideos1),
NewClients = orddict:store(Pid, YoutubeId, S#state.clients),
loop(S#state{clients = NewClients, videos = NewVideos});
{_Pid, {comment, YoutubeId, Body}} ->
NewComments = add_comment(YoutubeId, Body, S#state.comments),
case orddict:find(YoutubeId, S#state.videos) of
{ok, Pids} -> send_comment(Pids, Body);
error ->
ok
end,
loop(S#state{comments = NewComments});
{Pid, {comments, YoutubeId}} ->
YComments = case orddict:find(YoutubeId, S#state.comments) of
{ok, Comments} -> Comments;
error -> []
end,
Pid ! {ok, YComments},
loop(S);
{'DOWN', _Ref, process, Pid, _Reason} ->
NewVideos = unsubscribe(Pid, S#state.clients, S#state.videos),
NewClients = orddict:erase(Pid, S#state.clients),
loop(S#state{videos = NewVideos, clients = NewClients});
upgrade ->
?MODULE:loop(S);
Unknown ->
io:format("Unknown message: ~p~n", [ Unknown ]),
loop(S)
end.
unsubscribe(Pid, Clients, Videos) ->
case orddict:find(Pid, Clients) of
{ok, Id} ->
case orddict:find(Id, Videos) of
{ok, Pids} ->
orddict:store(Id, lists:delete(Pid, Pids), Videos);
error ->
Videos
end;
error ->
Videos
end.
add_comment(YoutubeId, Body, CommentsMap) ->
CurrentComments = case orddict:find(YoutubeId, CommentsMap) of
{ok, Comments} -> Comments;
error -> []
end,
orddict:store(YoutubeId, [Body|CurrentComments], CommentsMap).
send_comment(Pids, Body) ->
lists:map(fun(Pid) -> Pid ! {comment, Body} end, Pids).
<file_sep>/README.md
Coliseum
========
This is a toy project for collective video viewing, tagging and
commenting. The idea is that people will find video on a given subject,
mark it with the tags and comment if they like. By recommending and
tagging, a good list of flicks can be collected and nicely organized.
Features
--------
* Search for video on Youtube
* Commenting (locally, not to Youtube)
Todo
----
* Let people tag video with hashtags in comments (for example, "great
video on #emberjs")
* Search results pagination.
* Try showing "recent" comments (display video and comments when
clicked) when the search query is empty. Replace with the remote
results when it's not.
Requirements
------------
* Ruby 1.9.3
* MongoDB
Contributing
------------
* Please check the list of planned features above
* If you want to pick something for implementation, let me know
* If you have something to say, you are welcome
* Submit pull requests
Lincese
-------
We'll go with MIT License for this one. Have fun. ;)
|
6b03b74d1dd360fe2be899a432ec812225432d5b
|
[
"SCSS",
"Markdown",
"HTML+ERB",
"Ruby",
"JavaScript",
"Erlang"
] | 14 |
SCSS
|
alg/coliseum
|
8f60c8d5cddee94b6522d259b701d5c0048e051b
|
e11d248bf0af3c0c726ea15e4fae5d5d45c68f67
|
refs/heads/master
|
<repo_name>Han-Weng/TreeNodeAlgorithm<file_sep>/src/TrieMap.java
import java.util.ArrayList;
public class TrieMap implements TrieMapInterface {
TrieMapNode root;
int index = 0;
public TrieMap() {
root = new TrieMapNode();
}
public void put(String key, String value) {
put(root, key, value);
}
public void put(TrieMapNode current, String curKey, String value) {
if ((curKey.length() >= 1)) {
if (current!=null) {
if(!current.getChildren().containsKey(curKey.charAt(0))){
current.getChildren().put(curKey.charAt(0), new TrieMapNode());
}}
put(current.getChildren().get(curKey.charAt(0)), curKey.substring(1), value);
}
if ((curKey.length() == 0)) {
current.setValue(value);
}
}
public String get(String key) {
return (get(root, key));
}
public String get(TrieMapNode current, String curKey) {
if (findNode(root,curKey)!=null) {
return findNode(root, curKey).getValue();
}
return null;
}
public boolean containsKey(String key) {
return (containsKey(root, key));
}
public boolean containsKey(TrieMapNode current, String curKey) {
if (findNode(root,curKey)!=null) {
if(findNode(root, curKey).getValue()==curKey){
return true;
}}
return false;
}
public ArrayList<String> getKeysForPrefix(String prefix) {
if (getSubtreeKeys(findNode(root, prefix))==null){
return new ArrayList<String>(); }
return (getSubtreeKeys(findNode(root, prefix)));
}
public TrieMapNode findNode(TrieMapNode current, String curKey){
if(current==null){
return null;
}
if ((curKey.length() == 0)) {
return (current);
}
return findNode(current.getChildren().get((curKey.charAt(0))),curKey.substring(1));
}
public ArrayList<String> getSubtreeKeys(TrieMapNode current) {
ArrayList<String> words = new ArrayList<String>();
if (current != null) {
for (Character s : current.getChildren().keySet()) {
words.addAll(getSubtreeKeys(current.getChildren().get(s)));
}
//
if ((!words.contains(current.getValue()))&¤t.getValue()!=null){
words.add(current.getValue());
}
if (current.getChildren() == null) {
return words;
}
}
return words;
}
public void print(){
print(root);
}
public void print(TrieMapNode current){
for (String s : getSubtreeKeys(current)){
System.out.println(s);
}
}
public static void main(String[] args){
}
}
|
0cc8526a628cf5846436462b483e6cf5b9496d70
|
[
"Java"
] | 1 |
Java
|
Han-Weng/TreeNodeAlgorithm
|
8ce3922745843de064c78d63a76c8b9847bae38e
|
3d266f2e3d352c88b2015b25f615f043e61c0164
|
refs/heads/main
|
<repo_name>joseangelpachecomartinez/Calculadora-<file_sep>/Calculadora/src/calculadora/Ventana.java
/*Crear una biblioteca dinámica que contenga las operaciones matemáticas básicas
en números enteros, dicha biblioteca deberá ser referencia a una aplicación de
CALCULADORA, por lo que cada una de esas operaciones que ejecute CALCULADORA
deberá realizarse desde la biblioteca.*/
package calculadora;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import operadores.Aritmetico;
public class Ventana extends JFrame{
public Ventana(){ //Crear Ventana
setTitle("Calculadora");//Titulo de la ventana
setSize(250, 300);//Tamaño de la ventana
setLocationRelativeTo(null);//Centrar la ventana
Panel p = new Panel();//Instanciar el JPanel
add(p);//Agregarlo a la ventana
p.setLayout(null);//Para modificar los componentes
}
}
class Panel extends JPanel { //Crear el panel
public void paintComponent(Graphics g){
//Intanciar botones
JButton Suma = new JButton("+");
JButton Resta = new JButton("-");
JButton Multiplicacion = new JButton("x");
JButton Division = new JButton("/");
//crear las cajas de texto
JTextField txtNum1 = new JTextField();
JTextField txtNum2 = new JTextField();
JTextField txtResultado = new JTextField();
//crear etiquetas
JLabel etNum1 = new JLabel("Numero 1");
JLabel etNum2 = new JLabel("Numero 2");
JLabel resultado = new JLabel("Resultado");
//Dar tamaño y pocion de las etiquetas
etNum1.setBounds(30, 25, 60, 20);
etNum2.setBounds(130, 25, 60, 20);
resultado.setBounds(70, 80, 70, 20);
//Dar tamaño y pocion de las cajas de textos
txtNum1.setBounds(30, 50, 80, 20);
txtNum2.setBounds(130, 50, 80, 20);
txtResultado.setBounds(70, 100, 80, 20);
//Dar tamaño y pocion de los botones
Suma.setBounds(20, 150, 80, 30);
Resta.setBounds(120, 150, 80, 30);
Multiplicacion.setBounds(20, 200, 80, 30);
Division.setBounds(120, 200, 80, 30);
//Ponerle tipo y tamaño de letra de los botones
Suma.setFont(new Font("arial", Font.BOLD, 30));
Resta.setFont(new Font("arial", Font.BOLD, 30));
Multiplicacion.setFont(new Font("arial", Font.BOLD, 30));
Division.setFont(new Font("arial", Font.BOLD, 30));
//Agregar los componentes al panel
add(Suma);
add(Resta);
add(Multiplicacion);
add(Division);
add(txtNum1);
add(txtNum2);
add(txtResultado);
add(etNum1);
add(etNum2);
add(resultado);
ActionListener Evento = new ActionListener() {//intanciar las acciones de los botones
@Override
public void actionPerformed(ActionEvent e) {
Aritmetico A = new Aritmetico(); // instanciamos la libreria creada
int num1, num2, resultado; // declarar variable
String re;
if(e.getSource()==Suma){ //condicion si presional el boton Suma
if(txtNum1.getText().equals("")||txtNum2.getText().equals("")){//si las cajas de texto estan vacias
JOptionPane.showMessageDialog(null, "Los datos no estan completos",//enunciado de error
"Error", JOptionPane.WARNING_MESSAGE);//nombre de la ventana emergete
}else{
//convertir a entero
num1=Integer.parseInt(txtNum1.getText());
num2=Integer.parseInt(txtNum2.getText());
//usar la libreria
resultado = A.Sumar(num1, num2);
re=String.valueOf(resultado);//convertir el resultado en String
txtResultado.setText(re);//agregarlo a la caja de texto
}
}
if(e.getSource()== Resta){//al presionar el boton Resta
if(txtNum1.getText().equals("")||txtNum2.getText().equals("")){
JOptionPane.showMessageDialog(null, "Los datos no estan completos",
"Error", JOptionPane.WARNING_MESSAGE);
}else{
num1=Integer.parseInt(txtNum1.getText());
num2=Integer.parseInt(txtNum2.getText());
resultado = num1 - num2;
re=String.valueOf(resultado);
txtResultado.setText(re);
}
}
if(e.getSource()== Multiplicacion){ // al presionar el boton multiplicacion
if(txtNum1.getText().equals("")||txtNum2.getText().equals("")){
JOptionPane.showMessageDialog(null, "Los datos no estan completos",
"Error", JOptionPane.WARNING_MESSAGE);
}else{
num1=Integer.parseInt(txtNum1.getText());
num2=Integer.parseInt(txtNum2.getText());
resultado = num1 * num2;
re=String.valueOf(resultado);
txtResultado.setText(re);
}
}
if(e.getSource()== Division){// al presionar el boton Division
if(txtNum1.getText().equals("")||txtNum2.getText().equals("")){
JOptionPane.showMessageDialog(null, "Los datos no estan completos",
"Error", JOptionPane.WARNING_MESSAGE);
}else{
num1=Integer.parseInt(txtNum1.getText());
num2=Integer.parseInt(txtNum2.getText());
try{
resultado = num1 / num2;
re=String.valueOf(resultado);
txtResultado.setText(re);
}catch(ArithmeticException ex){
JOptionPane.showMessageDialog(null, "Error de Sintaxis", "Error",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
};
//para darle evento al boton
Suma.addActionListener(Evento);
Resta.addActionListener(Evento);
Multiplicacion.addActionListener(Evento);
Division.addActionListener(Evento);
}
}<file_sep>/README.md
# Calculadora-
Actividad T2-03: Ejercicio
----------------------------
Crear una biblioteca dinámica que contenga las operaciones matemáticas básicas en números enteros, dicha biblioteca deberá ser referencia a una aplicación de CALCULADORA, por lo que cada una de esas operaciones que ejecute CALCULADORA deberá realizarse desde la biblioteca.
<file_sep>/Carpeta libreria/ArimeticoLib/src/operadores/Aritmetico.java
package operadores;
public class Aritmetico {
public int Sumar(int num1, int num2){ // metodo sumar
return(num1+num2);
}
public int Restar(int num1, int num2){//metodo restar
return(num1-num2);
}
public int Multiplicar(int num1, int num2){//metodo multiplicar
return(num1*num2);
}
public int Dividir(int num1, int num2){//metodo multiplicar
if(num2 !=0){
return(num1/num2);
}else{
System.err.println("No se puede dividir entre cero");
}
return 0;
}
}
|
9bf5e9ab30beff144b82c6db2dbd9de54570aaa6
|
[
"Java",
"Markdown"
] | 3 |
Java
|
joseangelpachecomartinez/Calculadora-
|
a608e7063a2845ce30367f4552a4b292763e6b16
|
a370c34e7dfe0f8c75b3bfa34785e3e6aca8db45
|
refs/heads/master
|
<repo_name>glebek2h/python_labs<file_sep>/py_labs/l1/1.1.py
arr = [input('1:'), input('2:'), input('3:')]
count = 0
print(arr)
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] == arr[j]:
count += 1
print(count)
<file_sep>/py_labs/l1/1.4.py
import numpy as np
arr = np.random.randint(low=1, high=100, size=10)
count = 0
for i in range(1, len(arr) - 1):
if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
count += 1
print(arr, count)
<file_sep>/py_labs/l3/3.1.py
import numpy as np
from scipy.linalg import expm
A = np.diagflat(np.arange(1, 15, 2, dtype=int), 0) + np.diag(np.full(6, 7, dtype=int), -1)
A[:, 4] = np.full(7, 9)
A[4][3] = 9
R = np.vstack((np.hstack((A, np.eye(7))), np.hstack((np.exp(A), expm(A)))))
np.savetxt('C.txt', R)
<file_sep>/wavelet_analysis/l2/image_compression.py
import numpy as np
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
def fft(x):
return np.fft.fft(x)
def ifft(x):
return np.fft.ifft(x)
def Z(m):
count_zeros = 0
count_matrix_numbers = len(m[:, 0]) * len(m[0, :])
for i in range(len(m[:, 0])):
for j in range(len(m[0, :])):
if m[i][j] == 0:
count_zeros += 1
return count_zeros / count_matrix_numbers * 100
def get_Y_eps(Y, eps):
n = len(Y[:, 0])
m = len(Y[0, :])
Y_eps = Y.copy()
for i in range(n):
for j in range(m):
if abs(Y_eps[i][j]) <= eps:
Y_eps[i][j] = 0
return Y_eps
def PSNR(X, X_eps, n, m):
s = 0
for i in range(n):
for j in range(m):
s += (X[i][j] - X_eps[i][j]) ** 2
rms = np.sqrt(s / (m * n))
M_gray = 255
return 20 * np.log10(M_gray / rms)
X = np.int32(
rgb2gray(plt.imread(
r'/Users/fpm.kazachin/PycharmProjects/wavelet_analysis/l2/ tulip_fields.jpg')) * 255) # матрица из интенсивностей серого цвета
imgplot_1 = plt.imshow(X, cmap='Greys_r')
plt.savefig('compressed_img/source_black.png', bbox_inches='tight')
n = len(X[:, 0])
m = len(X[0, :])
Y = np.zeros((n, m), dtype=complex)
for i in range(m): # применили fft к столбцам Х
Y[:, i] = fft(X[:, i])
for i in range(n): # применили fft к строкам Х
Y[i, :] = fft(X[i, :])
eps_0 = Y[52][60].real
eps_3 = Y[201][700].real
eps_17 = Y[21][60].real
eps_29 = Y[25][100].real
eps_39 = Y[31][60].real
eps_58 = Y[21][100].real
eps_72 = Y[26][60].real
eps_80 = Y[25][55].real
eps_90 = Y[24][22].real
eps_99 = Y[32][10].real
eps_arr = [eps_0, eps_3, eps_17, eps_29, eps_39, eps_58, eps_72, eps_80, eps_90, eps_99]
Z_arr = []
PSNR_arr = []
for k in range(len(eps_arr)):
Y_eps = get_Y_eps(Y, eps_arr[k])
X_eps = np.zeros((n, m), dtype=complex)
for i in range(m): # применили ifft к столбцам Y
X_eps[:, i] = ifft(Y_eps[:, i])
for i in range(n): # применили ifft к строкам Y
X_eps[i, :] = ifft(Y_eps[i, :])
imgplot_2 = plt.imshow(np.abs(X_eps), cmap='Greys_r')
plt.savefig('compressed_img/eps_{0}.png'.format(round(Z(Y_eps))), bbox_inches='tight')
PSNR_arr.append(np.abs(PSNR(X, X_eps, n, m)))
Z_arr.append(Z(Y_eps))
if k == 7:
print('eps_80: ', eps_arr[k], 'Z(eps_80):', Z_arr[k])
if k == 8:
print('eps_90: ', eps_arr[k], 'Z(eps_90):', Z_arr[k])
if k == 9:
print('eps_99: ', eps_arr[k], 'Z(eps_99):', Z_arr[k])
plt.figure()
plt.plot(Z_arr, PSNR_arr)
plt.xlabel('Z')
plt.ylabel('PSNR')
plt.show()
<file_sep>/py_labs/l3/3.2.py
import numpy as np
import scipy.special as sc
N = 10
z = 10
print(sum([((5 / 6) + 2 * k) * sc.gamma(1 + k)/np.math.factorial(k) * sc.jv(1/(2 + k), z) * sc.jv(1/(3 + k), z) for k in range(0, N)]))
<file_sep>/py_labs/l2/poly.py
import copy
import numbers
class Poly:
def __init__(self, c):
self.c = c
def get_value(self, x):
s = 0
for i in range(len(self.c)):
s += self.c[i] * (x ** (len(self.c) - i - 1))
return s
def diff(self):
c = copy.deepcopy(self.c)
c.pop()
for i in range(len(c)):
c[i] = c[i] * (len(c) - i)
return Poly(c)
def print_polynomial(self):
c = self.c
print('(', end='')
for i in range(len(c)):
print(c[i], end='')
if i != len(c) - 1:
print('* x ^', len(c) - i - 1, '+', end='')
else:
print(')', end='')
def __add__(self, class_instance):
return Poly(Poly.sum_min_arr(self.c, class_instance.c, 'sum'))
def __sub__(self, class_instance):
return Poly(Poly.sum_min_arr(self.c, class_instance.c, 'min'))
def __mul__(self, number):
if isinstance(number, numbers.Number):
return Poly(list(map(lambda x: x * number, self.c)))
elif isinstance(number, Poly):
a = self.c
b = number.c
poly_arr = []
for i in range(len(a)):
c = []
for k in range(0, len(a) * len(b)):
c.append('None')
pow_a = len(a) - i - 1
max_pow = 0
for j in range(len(b)):
pow_b = len(b) - j - 1
if (pow_a + pow_b) > max_pow:
max_pow = pow_a + pow_b
if c[pow_a + pow_b] is 'None':
c[pow_a + pow_b] = a[i] * b[j]
else:
c[pow_a + pow_b] = c[i] + a[i] * b[j]
poly_arr.append(Poly([0 if x == 'None' else x for x in c[:max_pow + 1][::-1]]))
for i in range(1, len(poly_arr)):
poly_arr[0] += poly_arr[i]
return poly_arr[0]
@staticmethod
def sum_min_arr(a, b, sum_or_min):
if len(a) < len(b):
if len(a) == 1:
b_copy = [b[len(b) - 1]]
else:
b_copy = b[len(b) - len(a):]
return b[:len(b) - len(a)] + Poly.add(a, b_copy) if sum_or_min == 'sum' else b[:len(b) - len(a)] + Poly.min(
a, b_copy)
else:
if len(b) == 1:
a_copy = [a[len(a) - 1]]
else:
a_copy = a[len(a) - len(b):]
return a[:len(a) - len(b)] + Poly.add(a_copy, b) if sum_or_min == 'sum' else a[:len(a) - len(b)] + Poly.min(
a_copy, b)
@staticmethod
def add(a, b):
return list(map(lambda x, y: (x or 0) + (y or 0), a, b))
@staticmethod
def min(a, b):
return list(map(lambda x, y: (x or 0) - (y or 0), a, b))
p1 = Poly([1, 0, 0, 2, 3, 4])
p2 = Poly([1, 2, 1])
p1.print_polynomial()
print('')
p2.print_polynomial()
(p1 * p2).print_polynomial()
print('\n', (p1 * p2).get_value(5))
p1 = Poly([1, 0, 2])
p2 = Poly([1, 0, -1])
(p1 - p2).print_polynomial()<file_sep>/py_labs/l4/4.2.py
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0, 10 * np.pi, 0.01)
fig, ax = plt.subplots()
plt.plot(t * np.sin(t), t * np.cos(t), label="Archimedean spiral", lw=3)
plt.axis('equal')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()
<file_sep>/CMMF/1.py
import numpy as np
def f_func(x):
return (np.sin(x)) ** 2
def k_func(x):
return (np.cos(x)) ** 2 + 1
def q_func(x):
return 1
N, h, ae_0, g_0, ae_1, g_1 = 10, 1 / 10, 1, 0, 1, 1
x, k, q, f, C, F, A, B = [], [], [], [], [], [], [], []
for i in range(0, N + 1):
x.append(i * h)
k.append(k_func(x[i]))
q.append(q_func(x[i]))
f.append(f_func(x[i]))
C.append(2 * k[i] + h * h * q[i])
F.append(f[i] * h * h)
R = h * ae_0 + h * h * q[0] / 2 - h * h * (-2 * np.sin(x[0]) * np.cos(x[0])) * ae_0 / (2 * k[0]) + k[0]
O_1 = k[0] / R
W1 = (h * g_0 + h * h * f[0] / 2 - h * h * (-2 * np.sin(x[0]) * np.cos(x[0])) * g_0 / (2 * k[0])) / R
Q = h * ae_1 + h * h * q[N] / 2 + h * h * (-2 * np.sin(x[0]) * np.cos(x[0])) * ae_1 / (2 * k[N]) + k[N]
O_2 = k[N] / Q
W2 = (h * g_1 + h * h * f[N] / 2 + h * h * (-2 * np.sin(x[0]) * np.cos(x[0])) * g_1 / (2 * k[N])) / Q
A.append(0)
B.append(O_1)
for i in range(1, N):
A.append(k[i] - (k[i + 1] - k[i - 1]) / 4)
B.append(k[i] + (k[i + 1] - k[i - 1]) / 4)
A.append(O_2)
B.append(0)
C[0], F[0], C[N], F[N] = 1, W1, 1, W2
alfa, beta, y = np.zeros(N + 1), np.zeros(N + 1), np.zeros(N + 1)
alfa[1], beta[1] = O_1, W1
for i in range(1, N):
alfa[i + 1] = B[i] / (C[i] - alfa[i] * A[i])
beta[i + 1] = (F[i] + beta[i] * A[i]) / (C[i] - alfa[i] * A[i])
y[N] = (W2 + O_2 * beta[N]) / (1 - alfa[N] * O_2)
for i in range(N - 1, -1, -1):
y[i] = alfa[i + 1] * y[i + 1] + beta[i + 1]
for i in range(0, N + 1):
print("u(", x[i], ") = ", y[i])
<file_sep>/wavelet_analysis/test.py
import numpy as np
def tau(x):
return (-1) ** x
def r(nums, i):
sums = 0
for j in range(len(nums) - i):
sums += tau((nums[j] + nums[j + i]) % 2)
return sums
class LFSR:
def __init__(self, a, c):
self.b = np.array(a)
self.c = np.array(c)
self.period = self._get_period()
def _LFSR_iter(self):
r = np.dot(self.b, self.c) % 2
for i in range(len(self.b) - 1):
self.b[i] = self.b[i + 1]
self.b[-1] = r
def get_bits(self, n=1):
bits = np.zeros(n)
for i in range(n):
bits[i] = self.b[0]
self._LFSR_iter()
return bits
def _get_period(self):
tmp = self.b.copy()
self._LFSR_iter()
period = 0
dct = {}
while tuple(self.b) not in dct:
dct[tuple(self.b)] = period
self._LFSR_iter()
period += 1
ans = period - dct[tuple(self.b)]
self.b = tmp
return ans
class Geffe_gen:
def __init__(self, lfsr1, lfsr2, lfsr3):
self.lfsr1 = lfsr1
self.lfsr2 = lfsr2
self.lfsr3 = lfsr3
def get_bits(self, n=1):
mas1 = self.lfsr1.get_bits(n)
mas2 = self.lfsr2.get_bits(n)
mas3 = self.lfsr3.get_bits(n)
print(mas1, mas2, mas3)
return (mas1 * mas2) + (mas1 + np.ones(n)) * (mas3) % 2
def _get_period(self):
tmp = self.b.copy()
self._LFSR_iter()
period = 0
dct = {}
while tuple(self.b) not in dct:
dct[tuple(self.b)] = period
self._LFSR_iter()
period += 1
ans = period - dct[tuple(self.b)]
self.b = tmp
return ans
# a1 = [0, 1, 1, 1, 0]
# c1 = [1, 1, 1, 0, 1]
a1 = [0, 0, 1, 0, 0]
c1 = [0, 1, 1, 1, 1]
lfsr1 = LFSR(a1, c1)
print(len(lfsr1.get_bits(lfsr1.period)))
print(f'LFSR1:\n период равен {lfsr1.period}\n последовательность до начала зацикливания{lfsr1.get_bits(lfsr1.period)}')
# a2 = [1, 1, 1, 0, 1, 0, 1]
# c2 = [0, 0, 1, 1, 0, 1, 1]
a2 = [1, 0, 1, 0, 1, 1, 1]
c2 = [1, 0, 1, 0, 0, 0, 1]
lfsr2 = LFSR(a2, c2)
print(f'LFSR2:\n период равен {lfsr2.period}\n последовательность до начала зацикливания{lfsr2.get_bits(lfsr2.period)}')
# a3 = [0, 1, 1, 1, 1, 1, 1, 0]
# c3 = [1, 0, 1, 0, 1, 1, 1, 1]
a3 = [0, 0, 1, 0, 1, 1, 0, 0]
c3 = [1, 1, 1, 1, 0, 1, 0, 1]
lfsr3 = LFSR(a3, c3)
print(f'LFSR3:\n период равен {lfsr3.period}\n последовательность до начала зацикливания{lfsr3.get_bits(lfsr3.period)}')
geffe_gen = Geffe_gen(lfsr1, lfsr2, lfsr3)
numbers = geffe_gen.get_bits(10000)
print('geffe', numbers)
print(f'количество 1: {sum(numbers)}')
print(f'количество 0: {len(numbers) - sum(numbers)}')
for i in range(1, 6):
print(f'r_{i}: {r(numbers, i)}')<file_sep>/py_labs/l5/5.3.py
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
# y''' + y'' -10y' + 9y = 0
# u = y
# u' = y' = v
# v' = y'' = w
# w' = y''' = -y'' + 10y' - 9y = -w + 10v - 9u
#
# u(0) = 0
# v(0) = 0
# w(0) = 1
def rhs(s, v):
return [v[1], v[2], -v[2] + 10 * v[1] - 9 * v[0]]
res = solve_ivp(rhs, (0, 2), [0, 0, 1])
y = res.y[0]
print(y)
# time points
t = np.arange(0.0, 2.0, 0.2)
plt.plot(t[:len(y)], y)
plt.show()<file_sep>/wavelet_analysis/l4/daubechies_wavelet.py
import numpy as np
import scipy.special as scp
import numpy.polynomial.polynomial as poly
from numpy import linalg as LA
from wavelet_analysis.l4.draw_daubechies import draw_scaling_function_and_wavelet
import pywt as pywt
def Q(N):
polynom_coefs = np.zeros(N)
for k in range(N):
polynom_coefs[k] = scp.binom(N - 1 + k, k)
return poly.Polynomial(polynom_coefs)
def U(N, Q):
result_poly = 0
for i in range(N):
result_poly += Q.coef[i] * poly.Polynomial([1 / 2, - 1 / 2]) ** i
return result_poly
def z_k(U_roots, N, type):
ret_value = []
for k in range(len(U_roots)):
ret_value.append(U_roots[k] + np.sqrt(U_roots[k] ** 2 - 1))
ret_value.append(U_roots[k] - np.sqrt(U_roots[k] ** 2 - 1))
print(ret_value)
count = 0
z_k = []
z_k_blacklist = []
if type == 'complex':
for i in range(len(ret_value)):
if not np.isin(np.abs(z_k_blacklist), np.abs(ret_value[i])) and ret_value[i].real < 1 and ret_value[i].imag < 1:
z_k.append(ret_value[i])
z_k_blacklist.append(ret_value[i])
count += 1
if count == N:
break
if type == 'real':
for i in range(len(ret_value)):
if ret_value[i].imag == 0 and np.abs(ret_value[i]) <= 1:
z_k.append(ret_value[i])
count += 1
if count == N:
break
return z_k
def B_1(N_1, z_k):
r_k = z_k
ret_value = poly.Polynomial([1])
for k in range(1, N_1 + 1):
ret_value *= (poly.Polynomial([- r_k[k - 1], 1])) / np.sqrt(np.abs(r_k[k - 1]))
return ret_value
def B_2(N_2, z_k):
cos_alpha_k = map(lambda x: x.real, z_k)
ret_value = poly.Polynomial([1])
for k in range(1, N_2 + 1):
ret_value *= poly.Polynomial([1, - 2 * cos_alpha_k[k - 1], 1])
return ret_value
def B_3(N_3, z_k):
ret_value = poly.Polynomial([1])
for k in range(1, N_3 + 1):
ret_value *= (poly.Polynomial([np.abs(z_k[k - 1]) ** 2, - 2 * z_k[k - 1].real, 1]) / np.abs(z_k[k - 1]))
return ret_value
def B(a_N, B_1=1, B_2=1, B_3=1):
return np.sqrt(np.abs(a_N) / 2) * B_1 * B_2 * B_3
def M_0(N, B):
return poly.Polynomial([1 / 2, 1 / 2]) ** N * B
def get_N1_N2_N3(U_roots):
N_1, N_2, N_3 = 0, 0, 0
for i in range(len(U_roots)):
if isinstance(U_roots[i], complex) and U_roots[i].imag != 0:
N_3 += 1
else:
if np.abs(U_roots[i] >= 1):
N_1 += 1
else:
N_2 += 1
return N_1, N_2, N_3 // 2
def get_Q_special(Q):
ret_coef = [Q.coef[0]]
for i in range(1, len(Q.coef)):
ret_coef.append(Q.coef[i] / (2 ** i))
print(ret_coef)
def get_daubechies_coef(N, a_N):
Q_ = Q(N)
U_ = U(N, Q_)
U_roots = U_.roots()
N_1, N_2, N_3 = get_N1_N2_N3(U_roots)
z_k_1 = z_k(U_roots, N_1, 'real')
z_k_2 = z_k(U_roots, N_2, 'real')
z_k_3 = z_k(U_roots, N_3, 'complex')
B_1_ = B_1(N_1, z_k_1)
B_2_ = B_2(N_2, z_k_2)
B_3_ = B_3(N_3, z_k_3)
B_ = B(a_N, B_1_, B_2_, B_3_)
M_0_sqrt_2 = M_0(N, B_) * np.sqrt(2)
return M_0_sqrt_2.coef
N = 6
a_N = - 63 / 128
daubechies_coef = get_daubechies_coef(N, a_N)
wavelet = pywt.Wavelet('db6')
print(f'|daubechies_coef - daubechies_coef_true| = {LA.norm(daubechies_coef - wavelet.dec_lo)}')
draw_scaling_function_and_wavelet(daubechies_coef)
<file_sep>/py_labs/l1/test.py
arr = [4, 7, 6, 9, 2, 1, 99, 33, 12, 13, 17]
def even(x):
even = []
for i in range(len(x)):
if i % 2 == 0:
even.append(x[i])
print(even)
return even
even(arr)
<file_sep>/py_labs/l2/class-of-functions.py
import numpy as np
from py_labs.l2.poly import Poly
class ClassOfFunctions:
def __init__(self, p_1, p_2, a):
self.p_1 = p_1
self.p_2 = p_2
self.a = a
def get_value(self, x):
return self.p_1.get_value(x) * np.sin(self.a * x) + self.p_2.get_value(x) * np.cos(self.a * x)
def __add__(self, class_instance):
if self.a != class_instance.a:
raise ValueError('param a of class instances is not equal')
return ClassOfFunctions(self.p_1 + class_instance.p_1, self.p_2 + class_instance.p_2, self.a)
def __sub__(self, class_instance):
return ClassOfFunctions(self.p_1 - class_instance.p_1, self.p_2 - class_instance.p_2, self.a)
def diff(self):
return ClassOfFunctions(self.p_1.diff() - self.p_2 * self.a, self.p_1 * self.a + self.p_2.diff(), self.a)
def print_in_readable_form(self):
self.p_1.print_polynomial(),
print('sin(', self.a, '* x ) +', end='')
self.p_2.print_polynomial()
print('cos(', self.a, '* x )', end='')
print('\n')
class1 = ClassOfFunctions(Poly([1, 2, 3, -2, 10]), Poly([1, 2, 3, 4]), 10)
print('polynomial_1:')
class1.print_in_readable_form()
class2 = ClassOfFunctions(Poly([1, 4, 10]), Poly([4]), 10)
print('polynomial_2:')
class2.print_in_readable_form()
print('polynomial_1 + polynomial_2:')
(class1 + class2).print_in_readable_form()
print('polynomial_1 - polynomial_2:')
(class1 - class2).print_in_readable_form()
print('(polynomial_1)`:')
print(class1.diff().get_value(2))
print('polynomial_1(2):')
print(class1.get_value(2))
<file_sep>/py_labs/l5/5.1.py
import numpy as np
import time
from scipy.sparse.linalg import bicg
from scipy.linalg import solve_banded
from scipy.sparse import dia_matrix
A = dia_matrix((np.array([[13, 14, 15, 28, 33, 44], [15, 16, 18, 22, 32, 42], [17, 18, 19, 44, 71, 81]]), [0, -1, 1]),
shape=(6, 6)).toarray()
b = [1, 2, 3, 4, 5, 6]
start_time_1 = time.time()
print(bicg(A, b))
end_time_1 = (time.time() - start_time_1) * 1000
ud = np.insert(np.diag(A, 1), 0, 0)
d = np.diag(A)
ld = np.insert(np.diag(A, -1), len(d) - 1, 0)
ab = [ud, d, ld]
start_time_2 = time.time()
print(solve_banded((1, 1), ab, b))
end_time_2 = (time.time() - start_time_2) * 1000
print('bicg:', end_time_1, 'solve_banded:', end_time_2)
<file_sep>/py_labs/l3/3.4.py
from functools import reduce
import numpy as np
def super_duper_func():
with open('A.txt') as f:
A = [list(map(int, row.split())) for row in f.readlines()]
A = np.array(A)
fourteen_col = A[:, 14]
return reduce(lambda x, y: x + y * y if abs(y) > 8 else x, fourteen_col, 0)
print(super_duper_func())
<file_sep>/wavelet_analysis/l1_fft/l1(FFT).py
import numpy as np
import scipy.linalg as scpl
import time
import pandas as pd
from matplotlib import pyplot as plt
def get_degree_of_2(n):
degree = 0
while n >= 2:
n /= 2
degree += 1
return degree
def w(n, m):
return np.exp((-2 * m * np.pi / n) * 1j)
def w_inv(n, m):
return np.exp((2 * m * np.pi / n) * 1j)
def fft(x, is_inverse=False):
t = get_degree_of_2(len(x))
y = np.array(x[bit_reverse(len(x))], dtype=complex)
for q in range(t):
y = mul_A_B(y, q + 1, is_inverse)
if is_inverse:
y /= len(y)
return y
def truefft(x):
return np.fft.fft(x)
def mul_A_B(y, q, is_inverse):
L = 2 ** q
y1 = y.copy()
for i in range(0, len(y), L):
y2 = y[i:i + L]
y3 = y2.copy()
if not is_inverse:
for j in range(len(y2) // 2):
y3[j] = y2[j] + w(len(y2), j) * complex(y2[len(y2) // 2 + j])
for j in range(len(y2) // 2, len(y2)):
y3[j] = y2[j - len(y2) // 2] - w(len(y2), j - len(y2) // 2) * complex(y2[j])
else:
for j in range(len(y2) // 2):
y3[j] = y2[j] + w_inv(len(y2), j) * complex(y2[len(y2) // 2 + j])
for j in range(len(y2) // 2, len(y2)):
y3[j] = y2[j - len(y2) // 2] - w_inv(len(y2), j - len(y2) // 2) * complex(y2[j])
y1[i:i + L] = y3
return y1
def bit_reverse(n):
reshuffle = []
bit_length = get_degree_of_2(n)
for num in range(n):
size = bit_length - 1
reversed_num = 0
while num > 0:
k = num % 2
num //= 2
reversed_num += k << size
size -= 1
reshuffle.append(reversed_num)
return reshuffle
t_y = []
t_z = []
eps_arr = []
delta_arr = []
for k in range(16):
n = 2 ** k
x_n = (np.random.rand(n) + np.random.rand(n) * 1j)
start_time = time.time()
y_n = fft(x_n)
t_y.append((time.time() - start_time) * 1000)
x_n_inv = fft(y_n, True)
start_time = time.time()
z_n = truefft(x_n)
t_z.append((time.time() - start_time) * 1000)
eps = scpl.norm(x_n - x_n_inv)
delta = scpl.norm(y_n - z_n)
delta_arr.append(delta)
eps_arr.append(eps)
if n == 8:
print('x_8:', x_n)
print('x_8_inv:', x_n_inv)
print('y_8:', y_n)
print('z_8:', z_n)
print('eps_8:', eps)
print('delta_8:', delta)
plt.figure()
plt.scatter(range(1, 17), t_z, color='green')
plt.scatter(range(1, 17), t_y, color='yellow')
plt.xlabel('k')
plt.ylabel('time(ms)')
plt.legend(['fft', 'truefft'])
plt.show()
print(pd.DataFrame(dict(k=range(1, 17), t_y=t_y, t_z=t_z, eps=eps_arr, delta=delta_arr)))
<file_sep>/MIKOZI/3.py
def iteration(b, c):
r = c[0] * b[0]
for i in range(1, len(b)):
r = int(r != c[i] * b[i])
for i in range(len(b) - 1):
b[i] = b[i + 1]
b[-1] = r
return b
def get_sequence(n, a, c):
res = []
b = a
for i in range(n):
res.append(b[0])
b = iteration(a, c)
return res
def lfsr(a, c):
b = iteration(a, c)
p = 0
map_sequence_period = []
result_sequence = []
while b not in map_sequence_period:
result_sequence.append(b[0])
map_sequence_period.append(b.copy())
b = iteration(b, c)
p += 1
return p, result_sequence
def geffe_generator(n, sequence_1, sequence_2, sequence_3):
y = []
for i in range(n):
s1 = int(sequence_1[i] != sequence_2[i])
s2 = int(((sequence_1[i] + 1) % 2) != sequence_3[i])
y.append((s1 + s2) % 2)
return y
def r(geffe_sequence, i):
res = 0
for j in range(len(geffe_sequence) - i):
res += (-1) ** ((geffe_sequence[j] + geffe_sequence[j + i]) % 2)
return res
a_1 = [0, 0, 1, 0, 0]
c_1 = [0, 1, 1, 1, 1]
period_1, sequence_1 = lfsr(a_1, c_1)
print('period_1:', period_1)
print('lfsr_1:', sequence_1)
a_2 = [1, 0, 1, 0, 1, 1, 1]
c_2 = [1, 0, 1, 0, 0, 0, 1]
period_2, sequence_2 = lfsr(a_2, c_2)
print('period_2:', period_2)
print('lfsr_2:', sequence_2)
a_3 = [0, 0, 1, 0, 1, 1, 0, 0]
c_3 = [1, 1, 1, 1, 0, 1, 0, 1]
period_3, sequence_3 = lfsr(a_3, c_3)
print('period_3:', period_3)
print('lfsr_3:', sequence_3)
n = 10000
geffe_sequence = geffe_generator(n, get_sequence(n, a_1, c_1), get_sequence(n, a_2, c_2), get_sequence(n, a_3, c_3))
print('geffe:', geffe_sequence)
print('count zeros:', len([x for x in geffe_sequence if x == 0]))
print('count ones:', len([x for x in geffe_sequence if x == 1]))
for i in range(1, 6):
print('r', i, ':', r(geffe_sequence, i))
<file_sep>/py_labs/l4/4.3.py
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def f(x , y):
return 3 * x ** 2 * (np.sin(x)) ** 2 - 5 * np.exp(2 * y)
y = np.linspace(-1, 1, 100)
x = y
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
ax.clabel(CS, inline=1, fontsize=10)
ax.set_title('Contour')
plt.savefig('foo1.png', bbox_inches='tight')
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z)
plt.savefig('foo2.png', bbox_inches='tight')
<file_sep>/py_labs/l1/1.2.py
x = int(input('1:'))
y = int(input('2:'))
z = x + x/10
count = 1
while z <= y:
z = z + z/10
count += 1
print(count)<file_sep>/py_labs/l4/4.1.py
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 2, 100)
y = (1 + np.exp(3 * t)) ** (1. / 3) + t ** (3. / 4)
z = np.log10(4 - t ** 2) / (1 + np.cos(t))
w = z - y
fig, ax = plt.subplots()
ax.plot(t, y, color="green", label="y(t)", linestyle=':', linewidth=2)
ax.plot(t, z, color="pink", label="z(t)", linestyle='--', linewidth=2)
ax.plot(t, w, color="blue", label="w(t)", linestyle='-.', linewidth=2)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()
<file_sep>/CMMF/lab_2.py
import numpy as np
from matplotlib import pylab
from mpl_toolkits.mplot3d import Axes3D
from numpy import linalg as LA
from prettytable import PrettyTable
def draw(X, Y, Z):
fig = pylab.figure()
cs = Axes3D(fig, azim=-80)
cs.plot_surface(X, Y, Z)
pylab.show()
def u_true(x, t):
return (x + 10 * t) ** 2
def solve(N, M, x, t, sigma, gamma):
y = np.zeros((N, M))
for i in range(N):
y[i][0] = x[i] ** 2
for j in range(M):
y[0][j] = 100 * (t[j] ** 2)
for i in range(0, N - 1):
for j in range(0, M - 1):
y[i + 1][j + 1] = (1 / (sigma * gamma)) * (
y[i][j + 1] * (1 + sigma * gamma) - y[i][j] * (1 - (1 - sigma) * gamma) - y[i + 1][j] * (
1 - sigma) * gamma)
return y
# sigma = 0.45
# gamma = 10
th = ['sigma', 'gamma', '|| U_true - U ||']
table = PrettyTable(th)
for sigma in np.arange(0.4, 0.6, 0.01):
for gamma in np.arange(1, 11, 0.1):
h = 0.1
tau = h * gamma / 10
N, M = int(1 / h), int(1 / tau)
x, t = np.zeros(N), np.zeros(M)
for i in range(N):
x[i] = i * h
for j in range(M):
t[j] = j * tau
U_true = np.zeros((N, M))
for i in range(N):
for j in range(M):
U_true[i][j] = u_true(x[i], t[j])
U = solve(N, M, x, t, sigma, gamma)
print(f'|| U_true - U || = {LA.norm(U_true - U)}')
X, Y = np.meshgrid(t, x)
draw(X, Y, U_true)
draw(X, Y, U)
table.add_row([sigma, gamma, LA.norm(U_true - U)])
print(table)
<file_sep>/py_labs/l3/3.3.py
import numpy as np
import random
def super_func(c, b=None):
if np.linalg.det(c):
if b is None:
b = np.array([random.random() for i in range(10)])
x = np.linalg.solve(c, b)
return x, sum(abs(x))
M = np.array([[2., 5.], [1., -10.]])
B = np.array([1., 3.])
x,a = super_func(M, B)
print(x, a)
<file_sep>/wavelet_analysis/l4/draw_daubechies.py
import numpy as np
from matplotlib import pyplot as plt
import pywt as pywt
def phi_0(x, left, right):
if x < left or x > right:
return 0
return 1
def draw_scaling_function_and_wavelet(h):
left, right = 0, 12
x = np.arange(left, right, 1 / 4)
N = len(x)
fi, fi_obj = get_scaling_function(h[::-1], x, N, left, right)
psi = get_wavelet_function(h, x, fi_obj)
wavelet = pywt.Wavelet('db6')
phi_true, psi_true, x_true = wavelet.wavefun(level=5)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.plot(x, fi)
ax1.set_title('phi')
ax2.plot(x_true, phi_true, 'tab:orange')
ax2.set_title('phi_true')
ax3.plot(x, psi, 'tab:green')
ax3.set_title('psi')
ax4.plot(x_true, psi_true, 'tab:red')
ax4.set_title('psi_true')
for ax in fig.get_axes():
ax.label_outer()
plt.show()
def get_scaling_function(h, x, N, left, right):
fi_1, fi_1_object = np.zeros(len(x), dtype=float), {}
for xi in range(len(x)):
for k in range(len(h)):
fi_1[xi] += np.sqrt(2) * h[k] * phi_0(2 * x[xi] - k, left, right)
fi_1_object[x[xi]] = fi_1[xi]
fi_2 = np.zeros(len(x), dtype=float)
fi_2_object = {}
for m in range(1, N):
fi_2_object = {}
for x_i, i in zip(x, range(len(x))):
for k in range(len(h)):
if 2 * x_i - k in x:
fi_2[i] += np.sqrt(2) * h[k] * fi_1_object[2 * x_i - k]
fi_2_object[x_i] = fi_2[i]
fi_1_object = fi_2_object
return fi_2, fi_2_object
def get_wavelet_function(h, x, fi_obj):
q = np.zeros(len(h))
for k in range(len(h)):
q[k] = ((-1) ** k) * h[k]
psi = np.zeros(len(x))
for x_i, i in zip(x, range(len(x))):
for k in range(len(h)):
if 2 * x_i - k in x:
psi[i] += np.sqrt(2) * q[k] * fi_obj[2 * x_i - k]
return psi
<file_sep>/MIKOZI/kaz.py
import hashlib
import random
MAX_EVEN = 65536
def mod_mul(a, b, mod):
res = 0
a = a % mod
while b:
if (b & 1):
res = (res + a) % mod
a = (2 * a) % mod
b >>= 1
return res
# def mod_pow(base, exp, mod):
# res = 1
# base = base % mod
# if base == 0:
# return 0
# while exp > 0:
# if (exp & 1) == 1:
# res = mod_mul(res, base, mod)
# exp = exp >> 1
# base = mod_mul(base, base, mod)
# return res
def mod_pow(x, n, m):
res = 1
while n:
if n % 2:
res = res * x % m
x = (x ** 2) % m
n = n // 2
return res
def euler(p, q):
return (p - 1) * (q - 1)
# def egcd(a, b):
# if a == 0:
# return (b, 0, 1)
# else:
# g, y, x = egcd(b % a, a)
# return (g, x - (b // a) * y, y)
def egcd(a, b):
if b == 0:
return a, 1, 0
else:
d, x, y = egcd(b, a % b)
return d, y, x - y * (a // b)
def modinv(num, mod):
g, x, y = egcd(num, mod)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % mod
def gen(q):
while True:
R = random.randint(1, MAX_EVEN) * 2
p = q * R + 1
if not (mod_pow(2, q * R, p) != 1 or mod_pow(2, R, p) == 1):
break
g = 1
while g == 1:
x = random.randint(1, p - 1)
g = mod_pow(x, R, p)
print('x:', x)
print('g:', g)
d = random.randint(1, q - 1)
e = mod_pow(g, d, p)
return p, q, g, e, d
def hash_msg(message):
hash = hashlib.sha256()
hash.update(message.encode())
return int(hash.hexdigest(), 16)
def sign(p, q, g, d, message):
m = hash_msg(message)
k = random.randint(1, q - 1)
r = mod_pow(g, k, p)
inv_k = modinv(k, q)
s = (inv_k * (m - d * r)) % q
return r, s
def verify(p, q, g, e, message, r, s):
if r < 0 or r > p or s < 0 or s > q:
return False
m = hash_msg(message)
return mod_mul(mod_pow(e, r, p), mod_pow(r, s, p), p) == mod_pow(g, m, p)
# q = 97017021638387687521542127312722178904352834655752299660760969612789439451381
# message = 'Я, <NAME>, люблю МиКОЗИ'
q = 112971461064154869310834029706569828562173472410416149342082034001846987882313
message = 'Я, <NAME>, люблю МиКОЗИ'
p, q, g, e, d = gen(q)
r, s = sign(p, q, g, d, message)
print(verify(p, q, g, e, message, r, s))
<file_sep>/CMMF/2.py
import numpy as np
def f_func(x):
return (np.sin(x)) ** 2
def k_func(x):
return 1 / ((np.cos(x)) ** 2 + 1)
def q_func(x):
return 1
def integr(predicate, a, b):
count = 5000
integral, step = 0, (b - a) / count
for i in range(1, count + 1):
integral += step * predicate(a + (i - 1) * step)
return integral
N, h, ae_0, g_0, ae_1, g_1 = 10, 1 / 10, 1, 0, 1, 1
x, a, d, fi, C, F, A, B = [], [], [], [], [], [], [], []
for i in range(0, N + 1):
x.append(i * h)
a.append(1 / ((1 / h) * integr(lambda x1: k_func(x1), x[i - 1], x[i])))
d.append((1 / h) * integr(lambda x1: q_func(x1), x[i] - h / 2, x[i] + h / 2))
fi.append((1 / h) * integr(lambda x1: f_func(x1), x[i] - h / 2, x[i] + h / 2))
A.append(a[i])
d[0] = (2 / h) * integr(lambda x1: q_func(x1), 0, h / 2)
fi[0] = (2 / h) * integr(lambda x1: f_func(x1), 0, h / 2)
d[N] = (2 / h) * integr(lambda x1: q_func(x1), 1 - h / 2, 1)
fi[N] = (2 / h) * integr(lambda x1: f_func(x1), 1 - h / 2, 1)
R = h * ae_0 + h * h * d[0] / 2 + a[1]
O_1 = a[1] / R
W1 = (h * g_0 + h * h * fi[0] / 2) / R
Q = h * ae_1 + h * h * d[N] / 2 + a[N]
O_2 = a[N] / Q
W2 = (h * g_1 + h * h * fi[N] / 2) / Q
C.append(1)
B.append(O_1)
F.append(W1)
for i in range(1, N):
C.append(a[i + 1] + a[i] + d[i] * h * h)
B.append(a[i + 1])
F.append(fi[i] * h * h)
A[0] = 0
A[N] = O_2
C.append(1)
B.append(0)
F.append(W2)
alfa, beta, y = np.zeros(N + 1), np.zeros(N + 1), np.zeros(N + 1)
alfa[1], beta[1] = O_1, W1
for i in range(1, N):
alfa[i + 1] = B[i] / (C[i] - alfa[i] * A[i])
beta[i + 1] = (F[i] + beta[i] * A[i]) / (C[i] - alfa[i] * A[i])
y[N] = (W2 + O_2 * beta[N]) / (1 - alfa[N] * O_2)
for i in range(N - 1, -1, -1):
y[i] = alfa[i + 1] * y[i + 1] + beta[i + 1]
for i in range(0, N + 1):
print("u(", x[i], ") = ", y[i])
<file_sep>/course_project/main (4).py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import pylab
from mpl_toolkits.mplot3d import Axes3D
def draw(x, y, v, z_0, min_E_index):
X, Y = np.meshgrid(x, y)
Z = v[:(len(x) * len(y)), min_E_index].reshape((len(x), len(x)))
fig, ax = plt.subplots()
cs = ax.contour(X, Y, Z)
ax.clabel(cs, inline=1, fontsize=10)
plt.ylabel(f"v_[:, {min_E_index}]")
fig.colorbar(cs)
fig = pylab.figure()
cs = Axes3D(fig)
cs.plot_surface(X, Y, Z)
cs.set_xlabel("x")
cs.set_ylabel("y")
cs.set_zlabel(f"v_[:, {min_E_index}]")
cs.set_title(f"z_0={z_0}")
pylab.show()
def k_(i, j, N, M):
if j == 0 or i == N or j == M:
return -1 # сработало одно из 1-ых 3-ёх граничных условий
if i == 0:
return j - 1 # сработало 4-ое граничное условие
# M - 2 - кол-во столбцов в заполняемой матрице
return (i - 1) * (M - 2) + j - 1 # не соответсвует ни одному из граничных условий
def a_1(t):
return - 1 / (t ** 2)
def a_2(t, h, i, j, z_0, eps=11.4, eps2=3.8):
return - (- 2 / (t ** 2) - 2 / (h ** 2) + 2 / np.sqrt((i * h) ** 2 + (z_0 - j * t) ** 2) + 2 / np.sqrt(
(i * h) ** 2 + (z_0 + j * t) ** 2) * ((eps - eps2)/(eps + eps2)))
def a_3(t):
return - 1 / (t ** 2)
def a_4(h, i):
return - (1 / (h ** 2) + 1 / (i * h * 2 * h))
def a_5(h, i):
return - (1 / (h ** 2) - 1 / (i * h * 2 * h))
def solve(x0, xn, N, y0, ym, M, E, e, eps_0, z_0, m_, h_, g1=0, g2=0, g3=0, g4=0):
# x0 - начальная координата области решения по оси х;
# xn - конечная координата области решения по оси х;
# y0 - начальная координата области решения по оси y;
# ym - конечная координата области решения по оси y;
# N - число точек координатной сетки вдоль оси х;
# M - число точек координатной сетки вдоль оси y;
# f - функция в правой части уравнения
x = np.arange(x0 + (xn - x0) / N, xn, (xn - x0) / N)
h = x[1] - x[0]
y = np.arange(y0 + (ym - y0) / M, ym, (ym - y0) / M)
t = y[1] - y[0]
a = np.zeros(((N - 1) * (M - 1), (N - 1) * (M - 1)), dtype=float)
for i in range(1, N):
for j in range(1, M):
k_row = k_(i, j, N, M)
k_1 = k_(i, j + 1, N, M)
k_2 = k_row
k_3 = k_(i, j - 1, N, M)
k_4 = k_(i + 1, j, N, M)
k_5 = k_(i - 1, j, N, M)
if k_1 != -1:
a[k_row][k_1] = a_1(t)
if k_2 != -1:
a[k_row][k_2] += a_2(t, h, i, j, z_0) # Здесь и далее пишем '+=', т.к может совпасть индекс столбцов
if k_3 != -1:
a[k_row][k_3] += a_3(t)
if k_4 != -1:
a[k_row][k_4] += a_4(h, i)
if k_5 != -1:
a[k_row][k_5] += a_5(h, i)
E, v = np.linalg.eig(a)
min_E_index = np.argmin(E)
draw(x, y, v, z_0, min_E_index)
first = E[min_E_index]
print('first', first)
E[min_E_index] = 99
min_E_index = np.argmin(E)
second = E[min_E_index]
print('second', second)
E[min_E_index] = 99
min_E_index = np.argmin(E)
third = E[min_E_index]
print('third', third)
# E_copy[min_E_index_2] = 0
# min_E_index_3 = np.argmin(E_copy)
#
# E_copy[min_E_index_3] = 0
# min_E_index_4 = np.argmin(E_copy)
#
# E_copy[min_E_index_4] = 0
# min_E_index_5 = np.argmin(E_copy)
return [first, second, third]
x0, xn, N, y0, ym, M, E, e, eps_0, z_0, m_, h_, = 0, 20, 50, 0, 20, 50, 1000, 1.6 ** (-19), 8.85418781762039 ** (
-12), 10, 1 / 2, 1
E_arr = np.zeros((9, 3))
i = 0
for z_0 in np.arange(1, 10):
E_arr[i] = (solve(x0, xn, N, y0, ym, M, E, e, eps_0, z_0, m_, h_))
i += 1
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(np.arange(1, 10), E_arr[:, 0], s=10, c='b', marker="s", label='first')
ax1.scatter(np.arange(1, 10), E_arr[:, 1], s=10, c='r', marker="o", label='second')
ax1.scatter(np.arange(1, 10), E_arr[:, 2], s=10, c='y', marker="o", label='third')
plt.legend(loc='center right')
plt.xlabel('z_0')
plt.ylabel('E')
plt.show()
# E = (solve(x0, xn, N, y0, ym, M, E, e, eps_0, 8, m_, h_))
# z = np.zeros(6)
# for i in range(1, 7):
# z[i - 1] = - 1 / (i ** 2)
#
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.scatter(range(6), np.abs(E - z), s=10, c='b', marker="s")
# plt.ylabel('E - E_true')
# plt.title(f'z_0={8}')
# plt.show()
<file_sep>/wavelet_analysis/l3/haar.py
import numpy as np
import pywt
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from numpy import linalg as LA
def save_img(C, name):
plt.imshow(C, cmap='Greys_r')
plt.savefig('compressed_img/{0}.png'.format(name), bbox_inches='tight')
def for_rows(C_, n):
for i in range(n):
s, m = [], []
for k in range(0, n - 1, 2):
s.append((C_[i][k] + C_[i][k + 1]) / 2)
m.append((C_[i][k] - C_[i][k + 1]) / 2)
C_[i, :n] = s + m
def for_columns(C_, n):
for j in range(n):
s, m = [], []
for k in range(0, n - 1, 2):
s.append((C_[k][j] + C_[k + 1][j]) / 2)
m.append((C_[k][j] - C_[k + 1][j]) / 2)
C_[:n, j] = s + m
def dwt(C):
if len(C) != len(C[0]):
raise ValueError('Wrong matrix dimensions')
n = len(C)
C_ = np.array(C.copy(), dtype=float)
while n != 1:
for_rows(C_, n)
for_columns(C_, n)
n = n // 2
return C_
def for_rows_i(C, n, iteration):
for i in range(n):
s = []
for k in range(0, n - iteration, 1):
s.append(C[i][k] + C[i][k + iteration])
s.append(C[i][k] - C[i][k + iteration])
C[i, :n] = s
def for_columns_i(C, n, iteration):
for j in range(n):
s = []
for k in range(0, n - iteration, 1):
s.append(C[k][j] + C[k + iteration][j])
s.append(C[k][j] - C[k + iteration][j])
C[:n, j] = s
def dwt_i(C_):
if len(C_) != len(C_[0]):
raise ValueError('Wrong matrix dimensions')
n = len(C_)
C = np.array(C_.copy(), dtype=float)
c = 2
iteration = 1
while c != n * 2:
for_columns_i(C, c, iteration)
for_rows_i(C, c, iteration)
c *= 2
iteration *= 2
return C
def set_d_to_0(C, d, i):
C_ = C.copy()
n = C_.shape[0]
c = 0
while n is not 1 and c < i:
if d == 'g':
C_[:n // 2, n // 2:n] = 0
if d == 'v':
C_[n // 2:n, :n // 2] = 0
if d == 'd':
C_[n // 2:n, n // 2:n] = 0
n = n // 2
c += 1
return C_
C = np.int32(
rgb2gray(plt.imread(
r'/Users/fpm.kazachin/PycharmProjects/wavelet_analysis/l3/256x256.jpg')) * 255) # матрица из интенсивностей серого цвета
save_img(C, 'source_black')
n = C.shape[0]
# tests:
# C = np.array([[0, 2, 1, 2],
# [1, 1, 2, 0],
# [0, 1, 2, 1],
# [0, 2, 1, 2]])
# print('C = \n', C)
# C_ = dwt(C)
# print('C_ = \n', C_)
# print('dwt_i(C_) = \n', dwt_i(C_))
C_ = dwt(C)
save_img(C_, 'С_')
C_new = dwt_i(C_)
print('|dwt_i(C_) - C| =', LA.norm(C - C_new))
C_true = pywt.wavedec2(C, 'haar')
C_new_true = pywt.waverec2(C_true, 'haar')
print('|C_new_true - C| =', LA.norm(C_new_true - C))
# task 1
# a)
C_with_d_1_g_0 = set_d_to_0(C_, 'g', 1)
C_new = dwt_i(C_with_d_1_g_0)
save_img(C_with_d_1_g_0, 'task_1_a_C_')
save_img(C_new, 'task_1_a')
# a) true
C_true_array, coeff_slices = pywt.coeffs_to_array(C_true)
print('M:', LA.norm(C_true_array - C_))
C_true_array = set_d_to_0(C_true_array, 'g', 1)
C_new_true = pywt.waverec2(pywt.array_to_coeffs(C_true_array, coeff_slices, output_format='wavedec2'), 'haar')
print('||dwt_i(C_) - dwt_i_true(C_true)|| a:', LA.norm(C_new_true - C_new))
save_img(C_new_true, 'task_1_a_true')
# b)
C_with_d_1_v_0 = set_d_to_0(C_, 'v', 1)
C_new = dwt_i(C_with_d_1_v_0)
save_img(C_with_d_1_v_0, 'task_1_b_C_')
save_img(C_new, 'task_1_b')
# b) true
C_true_array, coeff_slices = pywt.coeffs_to_array(C_true)
C_true_array = set_d_to_0(C_true_array, 'v', 1)
C_new_true = pywt.waverec2(pywt.array_to_coeffs(C_true_array, coeff_slices, output_format='wavedec2'), 'haar')
print('||dwt_i(C_) - dwt_i_true(C_true)|| b:', LA.norm(C_new_true - C_new))
save_img(C_new_true, 'task_1_b_true')
# c)
C_with_d_1_d_0 = set_d_to_0(C_, 'd', 1)
C_new = dwt_i(C_with_d_1_d_0)
save_img(C_with_d_1_d_0, 'task_1_c_C_')
save_img(C_new, 'task_1_c')
# c) true
C_true_array, coeff_slices = pywt.coeffs_to_array(C_true)
C_true_array = set_d_to_0(C_true_array, 'd', 1)
C_new_true = pywt.waverec2(pywt.array_to_coeffs(C_true_array, coeff_slices, output_format='wavedec2'), 'haar')
print('||dwt_i(C_) - dwt_i_true(C_true)|| c:', LA.norm(C_new_true - C_new))
save_img(C_new_true, 'task_1_c_true')
# task 2
C_copy = C_.copy()
C_ = set_d_to_0(C_, 'g', 1)
C_ = set_d_to_0(C_, 'v', 1)
C_ = set_d_to_0(C_, 'd', 1)
C_new = dwt_i(C_)
save_img(C_, 'task_2_C_')
save_img(C_new, 'task_2')
# task 2 true
C_true_array, coeff_slices = pywt.coeffs_to_array(C_true)
C_true_array = set_d_to_0(C_true_array, 'g', 1)
C_true_array = set_d_to_0(C_true_array, 'v', 1)
C_true_array = set_d_to_0(C_true_array, 'd', 1)
C_new_true = pywt.waverec2(pywt.array_to_coeffs(C_true_array, coeff_slices, output_format='wavedec2'), 'haar')
print('||dwt_i(C_) - dwt_i_true(C_true)|| task_2:', LA.norm(C_new_true - C_new))
save_img(C_new_true, 'task_2_true')
# task 3
C_ = set_d_to_0(C_, 'g', 2)
C_ = set_d_to_0(C_, 'v', 2)
C_ = set_d_to_0(C_, 'd', 2)
C_new = dwt_i(C_)
save_img(C_, 'task_3_C_')
save_img(C_new, 'task_3')
# task 3 true
C_true_array, coeff_slices = pywt.coeffs_to_array(C_true)
C_true_array = set_d_to_0(C_true_array, 'g', 1)
C_true_array = set_d_to_0(C_true_array, 'v', 1)
C_true_array = set_d_to_0(C_true_array, 'd', 1)
C_true_array = set_d_to_0(C_true_array, 'g', 2)
C_true_array = set_d_to_0(C_true_array, 'v', 2)
C_true_array = set_d_to_0(C_true_array, 'd', 2)
C_new_true = pywt.waverec2(pywt.array_to_coeffs(C_true_array, coeff_slices, output_format='wavedec2'), 'haar')
print('||dwt_i(C_) - dwt_i_true(C_true)|| task_3:', LA.norm(C_new_true - C_new))
save_img(C_new_true, 'task_3_true')
# task 4
for j in range(7, 13):
C_copy[170][j] = 0
for j in range(0, 12):
C_copy[197][j] = 0
for j in range(0, 14):
C_copy[230][j] = 0
for j in range(49, 60):
C_copy[167][j] = 0
for j in range(100, 116):
C_copy[252][j] = 0
C_new = dwt_i(C_copy)
save_img(C_new, 'task_4')
<file_sep>/wavelet_analysis/15.04.py
import pywt
import numpy as np
import matplotlib.pyplot as plt
# wav = pywt.Wavelet('haar')
wav = pywt.Wavelet('db2')
print(wav.dec_lo)
print(wav.dec_hi)
data = np.arange(8)
print(pywt.wavedec(data, 'haar'))
dim = 32
img = np.zeros((dim, dim))
img[5, :] = 1
img[:, 10] = 1
img[:, 15] = 1
n = 15
for i in range(n):
img[i, n + i] = 1
dwt = pywt.wavedec2(img, 'haar')
print(dwt)
co_matrix, _ = pywt.coeffs_to_array(dwt)
print(co_matrix)
kwargs = dict(cmap=plt.cm.gray, interpolation='nearest')
plt.imshow(img, **kwargs)
plt.imshow(co_matrix, **kwargs)
plt.show()
<file_sep>/py_labs/l1/1.5.py
import numpy as np
arr = [10, 0, 0, 12, 1, 0, 13, 0]
res = []
while arr:
item = arr.pop()
if item != 0:
res.insert(0, item)
else:
res.append(item)
print(res)
<file_sep>/MIKOZI/5.py
import random
import hashlib
def gcdex(a, b):
if b == 0:
return a, 1, 0
else:
d, x, y = gcdex(b, a % b)
return d, y, x - y * (a // b)
def fast_p(x, n, m):
res = 1
while n:
if n % 2:
res = res * x % m
x = (x ** 2) % m
n = n // 2
return res
def gen(q):
while True:
R = random.randint(0, 4 * (q + 1))
R += R % 2
p = R * q + 1
if not (fast_p(2, q * R, p) != 1 or fast_p(2, R, p) == 1):
print('R :', R)
print('p :', p)
break
g = 1
while g == 1:
x = random.randint(1, p - 1)
g = fast_p(x, R, p)
print('x:', x)
print('g:', g)
d = random.randint(1, q - 1)
e = fast_p(g, d, p)
return p, q, g, e, d
def hash(m):
hash_ = hashlib.sha256()
hash_.update(m.encode())
return int(hash_.hexdigest(), 16)
def sign(p, q, g, d, M):
m = hash(M)
k = random.randint(1, q - 1)
r = fast_p(g, k, p)
gcd, x, y = gcdex(k, q)
k_ex = x % q
s = (k_ex * (m - d * r)) % q
return r, s
def verify(p, q, g, e, M, r, s):
if s < 0 or s > q or r > p or r < 0:
return False
m = hash(M)
return (fast_p(e, r, p) * fast_p(r, s, p)) % p == fast_p(g, m, p)
q = 112971461064154869310834029706569828562173472410416149342082034001846987882313
M = 'Я, <NAME>ский, люблю МиКОЗИ'
p, q, g, e, d = gen(q)
r, s = sign(p, q, g, d, M)
print(verify(p, q, g, e, M, r, s))
<file_sep>/py_labs/l5/5.2.py
import numpy as np
from scipy.integrate import quad
from scipy.optimize import fminbound
from scipy.special import gamma
def integrand(x, a):
return gamma(a * x) * np.exp(-a * x)
def f(a):
return quad(integrand, 1, 2, args=(a,))[0]
print(fminbound(f, 0, 1))
<file_sep>/MIKOZI/4.py
def gcdex(a, b):
if b == 0:
return a, 1, 0
else:
d, x, y = gcdex(b, a % b)
return d, y, x - y * (a // b)
def fast_p(x, n, m):
res = 1
while n:
if n % 2:
res = res * x % m
x = (x ** 2) % m
n = n // 2
return res
p = 148250911826341
q = 202614773351219
e = 12776470783322290155855389671
X1 = 26926695734432769312536758139
Y2 = 7060854756795018940042464563
n = p * q
fi = (p - 1) * (q - 1)
gcd, x, y = gcdex(e, fi)
d = 0
if gcd == 1:
d = x % fi
print('d: ', d)
Y1 = fast_p(X1, e, n)
print('Y1: ', Y1)
X1_ = fast_p(Y1, d, n)
print('X1_: ', X1_)
print('X1 - X1_ :', X1 - X1_)
X2 = fast_p(Y2, d, n)
print('X2: ', X2)
|
920ecbc313bd13ee4126be2c0fc530a40322025e
|
[
"Python"
] | 32 |
Python
|
glebek2h/python_labs
|
00ef7dbb5cc8602e85e11e5bf084de3f9e5de0b8
|
276731be7222bade6e67d04df53d504a8f383f7a
|
refs/heads/main
|
<repo_name>natedaniels42/typescript-algorithms<file_sep>/README.md
# typescript-algorithms
<file_sep>/mergesort/merge.ts
const merge = <T>(arr1: T[], arr2: T[]): T[] => {
const sorted: T[] = [];
while (arr1.length && arr2.length) {
if (arr1[0] < arr2[0]) {
sorted.push(arr1.shift());
} else {
sorted.push(arr2.shift());
}
}
return sorted.concat(arr1).concat(arr2);
}
export default merge;<file_sep>/bubblesort/bubblesort.ts
const bubblesort = <T>(arr: T[]): T[] => {
let sorted: boolean = false;
while (!sorted) {
sorted = true;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
return arr;
}
export default bubblesort;<file_sep>/bubblesort/bubblesort.js
"use strict";
exports.__esModule = true;
var bubblesort = function (arr) {
var sorted = false;
while (!sorted) {
sorted = true;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
return arr;
};
exports["default"] = bubblesort;
<file_sep>/mergesort/merge.js
"use strict";
exports.__esModule = true;
var merge = function (arr1, arr2) {
var sorted = [];
while (arr1.length && arr2.length) {
if (arr1[0] < arr2[0]) {
sorted.push(arr1.shift());
}
else {
sorted.push(arr2.shift());
}
}
return sorted.concat(arr1).concat(arr2);
};
exports["default"] = merge;
<file_sep>/quicksort/partition.ts
import swap from "./swap";
const partition = <T>(arr: T[], left: number, right: number): number => {
const pivot: T = arr[Math.floor((left + right) / 2)];
while (left <= right) {
while (arr[left] < pivot) {
left++;
}
while (arr[right] > pivot) {
right --;
}
if (left <= right) {
swap(arr, left, right);
left++;
right--;
}
}
return left;
}
export default partition;<file_sep>/quicksort/swap.ts
const swap = <T>(arr: T[], index1: number, index2: number): void => {
const temp: T = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
export default swap;<file_sep>/sieve/sieve.ts
const sieve = (num: number): number[] => {
const bools: boolean[] = [false, false];
const primes: number[] = [];
for (let i = 2; i <= num; i++) {
bools.push(true);
}
for (let i = 0; i < bools.length; i++) {
if (bools[i]) {
primes.push(i);
for (let j = i * 2; j < bools.length; j += i) {
bools[j] = false;
}
}
}
return primes;
}
export default sieve;<file_sep>/quicksort/quicksort.ts
import partition from "./partition";
const quicksort = <T>(arr: T[], left = 0, right = arr.length - 1): T[] => {
if (left < right) {
const pivotIndex: number = partition(arr, left, right);
quicksort(arr, left, pivotIndex - 1);
quicksort(arr, pivotIndex, right);
}
return arr;
}
export default quicksort;<file_sep>/mergesort/mergesort.ts
import merge from "./merge";
const mergesort = <T>(arr: T[]): T[] => {
const length: number = arr.length;
if (length < 2) {
return arr;
}
const mid: number = Math.floor(length / 2);
const left: T[] = arr.slice(0, mid);
const right: T[] = arr.slice(mid, length);
return merge(mergesort(left), mergesort(right));
}
export default mergesort;<file_sep>/index.js
"use strict";
exports.__esModule = true;
var bubblesort_1 = require("./bubblesort/bubblesort");
var mergesort_1 = require("./mergesort/mergesort");
var quicksort_1 = require("./quicksort/quicksort");
var sieve_1 = require("./sieve/sieve");
var arr = ['z', 'x', 'c', 'v', 'b', 'n', 'm', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'];
console.log("Bubble Sort: " + bubblesort_1["default"](arr).join(','));
console.log("Merge Sort: " + mergesort_1["default"](arr).join(','));
console.log("Quick Sort: " + quicksort_1["default"](arr).join(','));
console.log("Sieve: " + sieve_1["default"](100));
<file_sep>/index.ts
import bubblesort from "./bubblesort/bubblesort";
import mergesort from "./mergesort/mergesort";
import quicksort from "./quicksort/quicksort";
import sieve from "./sieve/sieve";
const arr: string[] = ['z','x','c','v','b','n','m','a','s','d','f','g','h','j','k','l','q','w','e','r','t','y','u','i','o','p'];
console.log(`Bubble Sort: ${bubblesort(arr).join(',')}`);
console.log(`Merge Sort: ${mergesort(arr).join(',')}`);
console.log(`Quick Sort: ${quicksort(arr).join(',')}`);
console.log(`Sieve: ${sieve(100)}`);
|
2f70af99c53b03f9413c5caeb38bde1bd8e41269
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 12 |
Markdown
|
natedaniels42/typescript-algorithms
|
3c3ab2218d2d441658395e672730b930c28939e8
|
6b2128d2bf01662b31a82562ed9a14e12ec3b16d
|
refs/heads/master
|
<repo_name>cgeidell/IDL_Codes<file_sep>/process_emep_data_SO4.pro
pro Emep_data_year_read,SPECIES,file,obs_year,data
; initialize
read_data=0
start_line=0
stop_check=0
prev_day=''
;open the data file
openr, 1, file ; open file
data = fltarr(366) ; define daily obs as 366 days
data[*]=!VALUES.F_NAN
tmp = '' ; initiate the tmp variable
i = 0 ; initiate the index for the loop
while (not EOF(1)) do begin
; Read one value at a time until EOF
readf, 1, tmp ; read from file
;now we are in the data part of the file = set read_data =1
if(read_data gt 0) then read_data=read_data+1
;split the string and find the start of the data
find_data=strsplit(tmp,' ',/extract)
if(find_data[0] eq 'starttime') then read_data=read_data+1
;find the element that contains the data
if(read_data eq 1) then begin
if(SPECIES eq 'TOTSO4') THEN BEGIN
data_el=where(find_data eq 'value')
; if value does not work then search for SO4 = std sulfate
if(data_el[0] lt 0) then data_el=where(find_data eq 'SO4--')
if(n_elements(data_el) gt 1) then stop
if(data_el[0] lt 0) then print,'cannot find sulfate element in data file :',file
numflag_el=where(find_data eq 'flag_SO4--')
endif ; TOTSO4
; USE FOR corrected SO4 DATA READ
if(SPECIES eq 'XSO4') THEN BEGIN
data_el=where(find_data eq 'value')
if(data_el[0] lt 0) then data_el=where(find_data eq 'XSO4--')
if(n_elements(data_el) gt 1) then stop
if(data_el[0] lt 0) then print,'cannot find corrected sulfate element in data file :',file
numflag_el=where(find_data eq 'flag_XSO4--')
endif ;xso4
; find the correct numflag to use
if(numflag_el[0] lt 0) then numflag_el=where(find_data eq 'numflag')
;find the numflag element
nfc=0
while ( n_elements(numflag_el) gt 1) do begin
nfc = nfc+1
if(find_data[data_el[0]+nfc] eq 'numflag') then numflag_el=data_el[0]+nfc
endwhile
if(n_elements(numflag_el) gt 1) then stop
if(numflag_el[0] lt 0) then print,'cannot find numflag element in data file :',file
;print,data_el,numflag_el
endif ; read_data
;;; - use numflag to ignore values that are not valid
if(read_data ge 2) then begin
if(find_data[numflag_el] lt 0.01) then data[read_data-2]=find_data[data_el]
;;print,find_data,' ', data[read_data-2]
endif
endwhile ; not end of file
close,1 ; close the data file
; set nans in data to nans in data arr
find_neg=where(data lt 0.0)
data(find_neg)=!values.f_nan
; find the zeros and set them to nans
find_zero=where(data eq 0.0)
data[find_zero]=!VALUES.F_NAN
end
;------------------------------------------------------------------------------------------------------------
PRO get_station_info,lat,lon,alt,station_name,station_code
; read the file that contains the station information = name/code/lon/lat/alt
stat_info_file='/home/tbreider/DATA/EMEP/a_stations.dat'
OPENR,2,stat_info_file
nstations=231
lon=fltarr(nstations) & lat=lon & alt=lon & station_name=strarr(nstations) & station_code=strarr(nstations)
tmp_stat=''
nskip=''
READF,2,nskip
FOR i=0,nstations-1 DO BEGIN
tmp=''
READF,2,tmp
tmp_stat=STRSPLIT(tmp,/extract)
if(n_elements(tmp_stat) eq 9 ) then j=0
if(n_elements(tmp_stat) eq 10) then j=1
if(n_elements(tmp_stat) eq 11) then j=2
lat[i] =FLOAT(tmp_stat[2+j])
lon[i] =FLOAT(tmp_stat[5+j])
alt[i] =FLOAT(tmp_stat[8+j])
station_name[i]=tmp_stat(1+j)
station_code[i]=tmp_stat(0)
lon_check =tmp_stat(7+j)
ENDFOR
CLOSE,2
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MAIN CODE STARTS HERE
;------------------------------------------------------------------------------------------
pro process_emep_data_SO4
;
; This code will read in daily observations of nss-sulfate and total sulfate in air from the
; European Monitoring and Evaluation Programme (EMEP). The code can be used to output all
; stations in the network or just specified stations for selected years)
;
; The data can be downloaded from http://ebas.nilu.no
;
; Written by <NAME> June 2012.
;
; Inputs
; ------
; species : Either XSO4 or TOTSO4 = corrected(nss-so4) or total sulfate
; pick_station_codes : Array of station codes for the stations that you want (Default is all = [*])
; data_years : Array of years that you want (Default is 1970-2015)
;
; Outputs
; -------
; observations_daily : daily sulfate concentrations in ugS/m3 [station,day,year]
; observations_daily_contin : daily sulfate concentrations in ugS/m3 [station,day]
;
; Output units are the same as in the input data files = micro grams S / m3)
;
; Notes
; -----
; Make sure that the location of the data files and the emep list file is linked to correctly
;
;=============================================================================================
;;; Key Inputs
;species = 'XSO4' ; corrected sulfate in surface air (corrected = sea salt sulfate has been removed)
species = 'TOTSO4'
;specify the stations that you want data for (eg. pick_station_codes=['AT0002R','NO0042G'] = see emep_station_codes )
pick_station_codes=['*'] ; use ['*'] for all stations in EMEP list file
;;pick_station_codes=[AT0002R,NO0042G]
;specify the data years that you want (eg. data_years=[2009,2010])
data_years=[1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Get the station name, code and lat/lon/alt info
get_station_info,lats,lons,alts,emep_station_names,emep_station_codes
; loc='/home/tbreider/DATA/EMEP_1980_2013/SO4_CORRECTED_AIR/'
; spawn,'ls /home/tbreider/DATA/EMEP_1980_2013/SO4_CORRECTED_AIR/',tmp
loc='/home/tbreider/DATA/EMEP_1980_2013/TOMS_IDL_CODES/DATA_FILES/'
spawn,'ls /home/tbreider/DATA/EMEP_1980_2013/TOMS_IDL_CODES/DATA_FILES/',tmp
files=tmp(0:n_elements(tmp)-1)
site_count=1
this_station_code='DUMMY' ; set the first station_code to a dummy value
prev_station_code='DUMMY1'
; set station names = station names that we want
station_codes=string(pick_station_codes)
if(pick_station_codes[0] eq '*') then station_codes=emep_station_codes
;declare the obs array and initialize to Nans
observations_daily=fltarr(n_elements(station_codes),366,n_elements(data_years)) ; num_stations,ndays,nyears)
observations_daily_contin=fltarr(n_elements(station_codes),366*n_elements(data_years)) ; continuous array of daily data over multiple yrs
observations_daily[*,*,*]=!VALUES.F_NAN & observations_daily_contin[*,*]=!VALUES.F_NAN
; loop over the files in the data directory
FOR i=0,n_elements(files)-2 DO BEGIN
;print,'reading file ....',files(i)
file=loc+files(i)
;stations have mutiple files for individual years so use prev_station_code to check if we are reading a new station
prev_station_code=this_station_code
; split the file name and pull out the station name
tmp1=STRSPLIT(file,'.',/extract)
tmp2=STRSPLIT(tmp1[0],'/',/extract)
this_station_code=tmp2[n_elements(tmp2)-1]
;find the element of the EMEP station that matches this station
station_el=where(emep_station_codes eq this_station_code)
; error check = print if the station_code is not found
if(station_el[0] lt 0.0) then print,'station_code :',this_station_code ,' is not found in EMEP list of stations'
if(station_el[0] lt 0.0) then print,'You should add this to the station list file'
;if(station_el[0] lt 0.0) then stop
; if new station = reset site_count
if(prev_station_code ne this_station_code) then site_count=0
if((site_count ne 1) and (station_el[0] ge 0)) then print,'station_code :',this_station_code,' has element ', station_el[0],' in EMEP list'
if(station_el[0] ge 0) then site_count=1
; find year of obs in the file name
obs_year=float(strmid(tmp1[1],0,4)) ; get the sub-string of the first 4 chars
this_obs_year=where(obs_year eq data_years) ; find ovs year element in our observation period
;store the data for the stations and years that are required
pick_station_code_el = where(this_station_code eq station_codes)
if(pick_station_code_el ne -1) then begin
if(this_obs_year ne -1) then begin ; do we want the observation year
; read the data from the file and year
Emep_data_year_read,species,file,obs_year,data
; put the obs into a storage array
if(station_el ne -1) then observations_daily [pick_station_code_el,*,this_obs_year]=data[*]
if(station_el ne -1) then observations_daily_contin[pick_station_code_el,(this_obs_year*366):((this_obs_year+1)*366)-1]=data[*]
endif
endif
ENDFOR ; n_els(files)
; Save out the updated file
SAVE,file='EMEP_sulfate_air_observations_1980_2010.dat',observations_daily,observations_daily_contin
stop
end
<file_sep>/README.md
This directory contains some files that I have written in IDL to read observations from the
European Monitoring and Evaluation Programme (EMEP)
|
81e64e58e8d9b11050ad51be3fcda2e3c24a9023
|
[
"Markdown",
"IDL"
] | 2 |
Markdown
|
cgeidell/IDL_Codes
|
188e9e8da816215b0290bf27419fb507612339d3
|
2f3b0d8dd889b9ddd264a75bdee36d91a6dfa965
|
refs/heads/master
|
<file_sep>#!/usr/bin/env node
const yargs = require('yargs');
const ProgressBar = require('progress');
const wrtc = require('wrtc');
const ws = require('ws');
const PeerFSManager = require('..');
const spread = [
'get <tag> <password> [--filename=filename] [--broker=broker] [--rate=rate]',
'get and spread a file through PeerFs',
yargs =>
yargs
.positional('tag', {
describe: 'PeerFS resource tag',
required: true,
})
.positional('password', {
describe: 'Password for file',
required: true,
})
.option('filename', {
describe: 'Path to file to save',
default: 'out.raw',
})
.option('broker', {
describe: 'Coven broker for p2p sync',
default: 'wss://coven-broker.now.sh',
})
.option('rate', {
describe: 'Publishing rate',
default: undefined,
}),
({ tag, filename, password, broker, rate }) => {
const manager = new PeerFSManager({ wrtc, ws, signaling: broker });
let progress;
manager
.download(tag, filename, password, rate)
.on('written', ({ blockCount }) => {
if (!progress) {
progress = new ProgressBar(
` ${tag} [:bar] :rate/bps :percent :etas`,
{
complete: '=',
incomplete: ' ',
width: 20,
total: blockCount,
}
);
}
progress.tick(1);
})
.once('done', () => process.exit())
.start();
},
];
const publish = [
'pub <filename> <password> [--broker=broker] [--rate=rate]',
'publish a file through PeerFS',
yargs =>
yargs
.positional('filename', {
describe: 'Path to published file',
required: true,
})
.positional('password', {
describe: 'Password for file',
required: true,
})
.option('broker', {
describe: 'Coven broker for p2p sync',
default: 'wss://coven-broker.now.sh',
})
.option('rate', {
describe: 'Publishing rate',
default: undefined,
}),
({ filename, password, broker, rate }) => {
const manager = new PeerFSManager({ wrtc, ws, signaling: broker });
manager
.publish(filename, password, rate)
.once('ready', tag => console.log(tag))
.on('publishing', ({ blockNumber, peerId }) =>
console.log(`Publishing block #${blockNumber} to peer ${peerId}`)
)
.start();
},
];
yargs.command(...publish).command(...spread).argv;
<file_sep>const wrtc = require('wrtc');
const ws = require('ws');
const Manager = require('..');
const PROD = 'wss://coven-broker.now.sh';
const manager = new Manager({ wrtc, ws, signaling: PROD });
const [file, password] = process.argv.slice(2);
manager
.publish(file, password)
.once('ready', tag => console.log(tag))
.on('publishing', ({ blockNumber, peerId }) =>
console.log(`Publishing block #${blockNumber} to peer ${peerId}`)
)
.on('processing', ({ blockNumber }) =>
console.log(`Processing block #${blockNumber}`)
)
.start();
<file_sep>const { decriptAndDecompress, writeBlock } = require('./utils');
const AbstractProcessor = require('./abstract');
module.exports = class Spreader extends AbstractProcessor {
constructor(filename, password, tag, coven, publishInterval) {
super(filename, password, coven, publishInterval);
this.tag = tag;
this.writtenBlocks = new Set();
this.blockCount = 0;
}
async _handlePeerData(peerId, data) {
this.blockCount = data.blockCount;
const { blockN, blockData, isDone, empty } = data;
if (isDone) {
this._peers.delete(peerId);
} else if (this._peers.has(peerId)) {
this._peers.get(peerId).add(blockN);
}
if (empty) {
return;
}
if (!this.writtenBlocks.has(blockN)) {
this.writtenBlocks.add(blockN);
if (blockN + 1 === this.blockCount) {
this.lastBlockSize = blockData.data.length;
}
try {
await writeBlock(this.compressedFile, blockData, blockN);
this.emit('written', {
blockNumber: blockN,
credit: peerId,
bytes: blockData.data.length,
progress: this.writtenBlocks.size / this.blockCount,
blockCount: this.blockCount,
});
if (this._isDone()) {
await decriptAndDecompress(
this.compressedFile.path,
this.filename,
this.password,
this.tag
);
this.coven.broadcast({
tag: this.tag,
isDone: true,
empty: true,
});
this.emit('done');
}
} catch (err) {
this.emit('error', err);
}
}
}
_shouldSpread() {
return this.blockCount && this.writtenBlocks.size && this._peers.size;
}
_getBlocksProvider() {
return this.writtenBlocks;
}
_isDone() {
return this.blockCount === this.writtenBlocks.size;
}
};
<file_sep># peerfs
Encrypted file transfers over webrtc, powered by Coven
<file_sep>const EventEmitter = require('events');
const { sleep, blockifyTempFileHandler, getTempFile } = require('./utils');
const PUBLISH_INTERVAL = 1000;
module.exports = class AbstractProcessor extends EventEmitter {
constructor(filename, password, coven, publishInterval = PUBLISH_INTERVAL) {
super();
this.filename = filename;
this.password = <PASSWORD>;
this.coven = coven;
this.publishInterval = publishInterval;
this._flags = { stop: true };
this._peers = new Map();
this.__initPromise = this._init();
this.coven.activePeers.forEach(peerId => this.addPeer(peerId));
this.coven
.on('connection', peerId => this.addPeer(peerId))
.on('disconnection', peerId => this._peers.delete(peerId))
.on('message', async ({ peerId, message }) => {
if (message.tag === this.tag) {
await this._handlePeerData(peerId, message);
}
});
}
_handlePeerData(peerId, data) {}
async _beforeLoad() {}
_shouldSpread() {
return this._peers.size;
}
_getBlocksProvider() {
return Object.keys(Array.from({ length: this.blockCount })).map(x => +x);
}
_isDone() {
return true;
}
async _init() {
const compressedFile = await getTempFile();
this.compressedFile = compressedFile;
await this._beforeLoad();
this.emit('ready', this.tag);
}
addPeer(peerId) {
this._peers.set(peerId, new Set());
}
start() {
this._flags.stop = false;
this.__loopPromise = this.__initPromise.then(() => this._loop());
return this;
}
pause() {
this._flags.stop = true;
this.__loopPromise.then(() => this.emit('paused'));
return this;
}
_publishToPeer(peerId, blocks, blockData, blockN, blockCount) {
if (blocks !== true && !blocks.has(blockN)) {
this.emit('publishing', {
blockNumber: blockN,
peerId,
});
this.coven.sendTo(peerId, {
blockN,
blockData,
blockCount,
tag: this.tag,
isDone: this._isDone(),
});
}
}
async _loop() {
this.emit('started');
while (!this._flags.stop) {
await sleep(this.publishInterval);
if (this._shouldSpread()) {
for await (let data of blockifyTempFileHandler(
this.compressedFile,
this.blockCount,
this._getBlocksProvider(),
this.lastBlockSize
)) {
const { blockData, blockN, blockCount } = data;
this.emit('processing', { blockNumber: blockN });
for (const [peerId, blocks] of this._peers.entries()) {
this._publishToPeer(peerId, blocks, blockData, blockN, blockCount);
}
await sleep(this.publishInterval);
}
}
}
}
};
<file_sep>const crypto = require('crypto');
const fs = require('then-fs');
const temp = require('temp-fs');
const { gzip } = require('compressing');
const CIPHER = 'aes-256-ctr';
const BLOCK_SIZE = 256;
const RAW_TAG_SIZE = 16;
const sleep = t => new Promise(resolve => setTimeout(resolve, t));
const getTempFile = () =>
new Promise((resolve, reject) =>
temp.open({ track: true }, (e, f) => (e ? reject(e) : resolve(f)))
);
const getTagHex = () => crypto.randomBytes(RAW_TAG_SIZE).toString('hex');
const getKey = password => {
const passwordHash = crypto.createHash('sha256');
passwordHash.update(password);
return passwordHash.digest();
};
const compressAndEncript = (input, output, password, tagHex) =>
new Promise((resolve, reject) => {
const compressor = new gzip.FileStream();
const iv = Buffer.from(tagHex, 'hex');
const cipher = crypto.createCipheriv(CIPHER, getKey(password), iv);
const input$ = fs.createReadStream(input);
const output$ = fs.createWriteStream(output);
input$
.pipe(compressor)
.pipe(cipher)
.pipe(output$);
output$.on('finish', resolve);
input$.on('error', reject);
});
const decriptAndDecompress = (input, output, password, tagHex) =>
new Promise((resolve, reject) => {
const decompressor = new gzip.UncompressStream();
const iv = Buffer.from(tagHex, 'hex');
const decipher = crypto.createDecipheriv(CIPHER, getKey(password), iv);
const input$ = fs.createReadStream(input);
const output$ = fs.createWriteStream(output);
input$
.pipe(decipher)
.pipe(decompressor)
.pipe(output$);
output$.on('finish', resolve);
input$.on('error', reject);
});
const writeBlock = (fileHandler, blockData, blockN) =>
fs.write(
fileHandler.fd,
Buffer.from(blockData),
0,
blockData.data.length,
blockN * BLOCK_SIZE
);
async function getBlockCount(fileHandler) {
const { size } = await fs.stat(fileHandler.path);
const blockCount = Math.ceil(size / BLOCK_SIZE);
return [blockCount, size % BLOCK_SIZE];
}
async function* blockifyTempFileHandler(
fileHandler,
blockCount,
blocksProvider,
lastBlockSize
) {
const block = Buffer.allocUnsafe(BLOCK_SIZE);
for (let blockN of blocksProvider) {
await fs.read(fileHandler.fd, block, 0, BLOCK_SIZE, blockN * BLOCK_SIZE);
const blockData = block.toJSON();
if (blockN + 1 === blockCount) {
blockData.data.splice(lastBlockSize);
}
yield {
blockN,
blockData,
blockCount,
};
}
}
module.exports = {
blockifyTempFileHandler,
compressAndEncript,
decriptAndDecompress,
getTagHex,
getTempFile,
sleep,
getBlockCount,
writeBlock,
};
|
ab82b867bff026aefb0b8ebccc658ec66ad46d23
|
[
"Markdown",
"JavaScript"
] | 6 |
Markdown
|
oakfang/peerfs
|
a19e8a30ab2c8891aeac49197c327325d7b695a8
|
95797e14fb6487d5e723efb1fd7b3cad7624894b
|
refs/heads/master
|
<file_sep><html>
<head>
</head>
<body>
<h1> Welcome To Dahsboard</h1>
</body>
</html><file_sep><?php
namespace App\Http\Controllers;
use App\Models\StudentData as ModelsStudentData;
use Illuminate\Http\Request;
class StudentData extends Controller
{
public static function saveStudentData(Request $request){
if(ModelsStudentData::saveStudentData(array('student_id'=> $request['student_id'],'student_name'=> $request['student_name'],'student_address'=> $request['student_address']))){
return "SuccessFully Create";
}
}
public static function login(Request $request){
if($request['email']=='<EMAIL>' && $request['password']='<PASSWORD>'){
return view('dashboard');
}
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
class StudentData extends Model
{
use HasFactory;
protected $fillable=['id','student_id','student_name','student_address'];
public $timestamps = false;
public static function saveStudentData($array){
StudentData::updateorCreate($array);
}
}
|
5c6f00eba27f8e34f3982f579efbcd57faa07be6
|
[
"Blade",
"PHP"
] | 3 |
Blade
|
HardikVerma4242/Student
|
522663aa8c3fb521ffda01fe996b3a6425dede96
|
c70645fa15d6500607c151e5e16f6c853a47bd8c
|
refs/heads/master
|
<file_sep>#include "frota.h"
#include <string>
using namespace std;
void Frota::adicionaVeiculo(Veiculo *v1)
{
this->veiculos.push_back(v1);
}
int Frota::numVeiculos()const
{
return this->veiculos.size();
}
int Frota::menorAno()const
{
int result, menor, temp;
if(this->veiculos.size() == 0)
result = 0;
else
{
menor = this->veiculos.at(0)->getAno();
for(auto &x: this->veiculos)
{
temp = x->getAno();
if(temp < menor)
menor = temp;
}
result = menor;
}
return result;
}
vector<Veiculo *> Frota::operator() (int anoM) const
{
vector<Veiculo *> result;
for(auto &x: this->veiculos)
{
if(x->getAno() == anoM)
result.push_back(x);
}
return result;
}
float Frota::totalImposto() const
{
float soma = 0;
//vector<Veiculo *>::iterator it;
for(auto &x: this->veiculos)
{
soma += x->calcImposto();
}
return soma;
}<file_sep>#include "jogo.h"
#include <sstream>
ostream &operator << (ostream &os, Circulo &c1)
{
string estadoStr;
if(c1.estado == true)
estadoStr = "true";
else
estadoStr = "false";
os << c1.pontuacao << "-" << estadoStr << "-" << c1.nVisitas << endl;
return os;
}
BinaryTree<Circulo> Jogo::iniciaJogo(int pos, int nivel, vector<int> &pontos, vector<bool> &estados)
{
Circulo c1(pontos[pos], estados[pos]);
if(nivel == 0)
return BinaryTree<Circulo>(c1);
else
{
BinaryTree<Circulo> filhoEsq = iniciaJogo(2*pos + 1, nivel - 1, pontos, estados);
BinaryTree<Circulo> filhoDir = iniciaJogo(2*pos + 2, nivel - 1, pontos, estados);
return BinaryTree<Circulo>(c1, filhoEsq, filhoDir);
}
}
Jogo::Jogo(int niv, vector<int> &pontos, vector<bool> &estados)
{
this->jogo = iniciaJogo(0, niv, pontos, estados);
}
string Jogo::escreveJogo()
{
BTItrLevel<Circulo> it(this->jogo);
stringstream result("");
while (!it.isAtEnd()) {
result << it.retrieve();
it.advance();
}
return result.str();
}
int Jogo::jogada()
{
int pos = 1; int pontos = -1;
BTItrLevel<Circulo> it(this->jogo);
if(it.isAtEnd())
return pontos;
while(true)
{
Circulo &c1 = it.retrieve();
bool estado = c1.getEstado();
int n;
if(estado == false)
n = pos;
else
n = pos + 1;
c1.mudaEstado();
c1.incNVisitas();
pontos = c1.getPontuacao();
int i = 0;
while(i < n && !it.isAtEnd())
{
it.advance(); // avanca p/ filho esquerdo ou direito
i++;
}
if(!it.isAtEnd())
pos += n;
else
break;
}
return pontos;
}
int Jogo::maisVisitado()
{
int maxVis = -1;
BTItrLevel<Circulo> it(this->jogo);
if(it.isAtEnd())
return maxVis;
else
{
it.advance();
while(!it.isAtEnd())
{
Circulo c1 = it.retrieve();
int nVis = c1.getNVisitas();
if(nVis > maxVis)
maxVis = nVis;
it.advance();
}
}
return maxVis;
}
<file_sep># The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
"/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/Tests/disjointSets.cpp" "/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/build-dir/CMakeFiles/aeda1920_fp11.dir/Tests/disjointSets.cpp.o"
"/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/Tests/maze.cpp" "/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/build-dir/CMakeFiles/aeda1920_fp11.dir/Tests/maze.cpp.o"
"/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/Tests/tests.cpp" "/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/build-dir/CMakeFiles/aeda1920_fp11.dir/Tests/tests.cpp.o"
"/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/main.cpp" "/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/build-dir/CMakeFiles/aeda1920_fp11.dir/main.cpp.o"
)
set(CMAKE_CXX_COMPILER_ID "GNU")
# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
"../lib/googletest-master/googlemock/include"
"../lib/googletest-master/googletest/include"
"../lib/googletest-master/googletest"
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
"/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/build-dir/lib/googletest-master/googlemock/gtest/CMakeFiles/gtest.dir/DependInfo.cmake"
"/home/joao/Desktop/FEUP/AEDA/TP10 - Disjoint Sets/build-dir/lib/googletest-master/googlemock/gtest/CMakeFiles/gtest_main.dir/DependInfo.cmake"
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
<file_sep>#include "parque.h"
#include <vector>
using namespace std;
ParqueEstacionamento::ParqueEstacionamento(unsigned int lot, unsigned int nMaxCli) : lotacao(lot), numMaximoClientes(nMaxCli)
{
vagas = lot;
}
unsigned int ParqueEstacionamento::getNumLugares() const
{
return lotacao;
}
unsigned int ParqueEstacionamento::getNumMaximoClientes() const
{
return numMaximoClientes;
}
unsigned int ParqueEstacionamento::getNumVagas() const
{
return vagas;
}
void ParqueEstacionamento::decrementaVagas(unsigned int n)
{
if(this->getNumVagas() >= n)
this->vagas -= n;
}
void ParqueEstacionamento::incrementaVagas(unsigned int n)
{
if(this->getNumVagas() + this->getNumLugares() <= this->getNumMaximoClientes())
this->vagas += n;
}
bool ParqueEstacionamento::estaNoParque(const string &nome)
{
bool result;
vector<InfoCartao>::const_iterator it;
for(it = this->clientes.begin(); it < this->clientes.end(); it++)
{
if(it->nome == nome)
{
result = it->presente;
break;
}
}
return result;
}
int ParqueEstacionamento::posicaoCliente(const string &nome) const
{
vector<InfoCartao>::const_iterator it;
int i = 0;
for(it = this->clientes.begin(); it < this->clientes.end(); it++, i++)
{
if(it->nome == nome)
{
return i;
}
}
return -1;
}
bool ParqueEstacionamento::adicionaCliente(const string &nome)
{
bool result;
if((this->posicaoCliente(nome) == -1) && (this->getNumVagas() > 0))
{
InfoCartao cli;
cli.nome = nome;
cli.presente = false;
clientes.push_back(cli);
result = true;
decrementaVagas(1);
}
else
result = false;
return result;
}
bool ParqueEstacionamento::entrar(const string & nome)
{
bool result;
if(this->posicaoCliente(nome) == -1 || this->getNumMaximoClientes() - this->getNumLugares() <=0 || this->estaNoParque(nome))
result = false;
else
{
this->clientes.at(this->posicaoCliente(nome)).presente = true;
result = true;
}
return result;
}
bool ParqueEstacionamento::retiraCliente(const string & nome)
{
int pos = this->posicaoCliente(nome);
bool result;
if(pos >=0 && this->clientes.at(pos).presente == false)
{
this->clientes.erase(this->clientes.begin() + pos);
result = true;
}
else
result = false;
return result;
}
bool ParqueEstacionamento::sair(const string & nome)
{
int pos = this->posicaoCliente(nome);
bool result;
if(pos == -1 || this->clientes.at(pos).presente == false)
result = false;
else
{
this->clientes.at(pos).presente = false;
result = true;
incrementaVagas(1);
}
return result;
}
unsigned int ParqueEstacionamento::getNumLugaresOcupados() const
{
unsigned int i = 0;
vector<InfoCartao>::const_iterator it;
for(it = this->clientes.begin(); it < this->clientes.end(); it++)
{
if(it->presente)
i++;
}
return i;
}
unsigned int ParqueEstacionamento::getNumClientesAtuais() const
{
return this->clientes.size();
}<file_sep>#ifndef _DIC
#define _DIC
#include <string>
#include <fstream>
#include "bst.h"
class PalavraSignificado {
string palavra;
string significado;
public:
PalavraSignificado(string p, string s): palavra(p), significado(s) {}
string getPalavra() const { return palavra; }
string getSignificado() const { return significado; }
void setSignificado(string sig) { significado=sig; }
bool operator < (const PalavraSignificado &ps1) const;
bool operator==(const PalavraSignificado &ps1) const;
friend ostream& operator<<(ostream &output, PalavraSignificado &ps);
};
class Dicionario
{
BST<PalavraSignificado> palavras;
public:
Dicionario(): palavras(PalavraSignificado("","")){};
BST<PalavraSignificado> getPalavras() const;
void lerDicionario(ifstream &fich);
string consulta(string palavra) const;
bool corrige(string palavra, string significado);
void imprime() const;
};
class PalavraNaoExiste
{
private:
string palavraAntes;
string significadoAntes;
string palavraApos;
string significadoApos;
public:
PalavraNaoExiste(string palAntes, string sigAntes, string palApos, string sigApos)
{
palavraAntes = palAntes;
significadoAntes = sigAntes;
palavraApos = palApos;
significadoApos = sigApos;
}
string getPalavraAntes() const { return this->palavraAntes; }
string getSignificadoAntes() const { return this->significadoAntes; }
string getPalavraApos() const { return this->palavraApos; }
string getSignificadoApos() const { return this->significadoApos; }
};
#endif
<file_sep># FEUP MIEIC AEDA
This repository has all of my work for the subject of Algorithms and Data Structures, except for the [final project](https://github.com/joaoDossena/Tokyo-2020)
Final Grade: 16
## To do:
- [ ] Finish last exercise of TP10
## List of Contents:
- TP1: Classes
- TP2: Inheritance and Polymorphism
- TP3: Exceptions and Templates
- TP4: Searching and Sorting Vectors and Complexity Analysis
- TP5: Lists
- TP6: Stacks and Queues
- TP7: Binary Trees
- TP8: Hash Tables
- TP9: Priority Queues
- TP10: Disjoint Sets
<file_sep>#include "veiculo.h"
#include <iostream>
using namespace std;
//Constructors
Veiculo::Veiculo(string mc, int m, int a)
{
this->marca = mc;
this->mes = m;
this->ano = a;
}
Motorizado::Motorizado(string mc, int m, int a,string c,int cil) : Veiculo(mc, m, a)
{
this->combustivel = c;
this->cilindrada = cil;
}
Automovel::Automovel(string mc, int m, int a,string c, int cil) : Motorizado(mc, m, a, c, cil)
{
}
Camiao::Camiao(string mc, int m, int a,string c, int cil,int cm) : Motorizado(mc, m, a, c, cil)
{
this->carga_maxima = cm;
}
Bicicleta::Bicicleta(string mc, int m, int a,string t) : Veiculo(mc, m, a)
{
this->tipo = t;
}
//Get Functions
//Veiculo
string Veiculo::getMarca() const
{
return this->marca;
}
int Veiculo::getAno() const
{
return this->ano;
}
int Veiculo::getMes() const
{
return this->mes;
}
//Bicicleta
string Bicicleta::getTipo() const
{
return this->tipo;
}
//Motorizado
string Motorizado::getCombustivel() const
{
return this->combustivel;
}
int Motorizado::getCilindrada() const
{
return this->cilindrada;
}
//Camiao
int Camiao::getCarga_maxima() const
{
return this->carga_maxima;
}
//Other Functions
//Veiculo
int Veiculo::info() const
{
cout << "Marca: " << this->getMarca() << endl;
cout << "Mês: " << this->getMes() << endl;
cout << "Ano: " << this->getAno() << endl;
return 3;
}
bool Veiculo::operator <(const Veiculo & v) const
{
bool result;
if(this->ano < v.ano)
result = true;
else if(this->ano == v.ano && this->mes < v.mes)
result = true;
else
result = false;
return result;
}
//Bicicleta
int Bicicleta::info() const
{
Veiculo::info();
cout << "Tipo: " << this->getTipo() << endl;
return 4;
}
float Bicicleta::calcImposto() const
{
return 0.0;
}
//Motorizado
int Motorizado::info() const
{
Veiculo::info();
cout << "Combustível: " << this->getCombustivel() << endl;
cout << "cilindrada: " << this->getCilindrada() << endl;
return 5;
}
//Automovel
int Automovel::info() const
{
return Motorizado::info();
}
//Camiao
int Camiao::info() const
{
Motorizado::info();
cout << "Carga máxima: " << this->getCarga_maxima() << endl;
return 6;
}
//calcImposto
float Motorizado::calcImposto() const
{
float result;
if(this->getAno() > 1995)
{
if(this->getCombustivel() == "gasolina")
{
if(this->getCilindrada() <= 1000)
result = 14.56;
else if(this->getCilindrada() <= 1300)
result = 29.06;
else if(this->getCilindrada() <= 1750)
result = 45.15;
else if(this->getCilindrada() <= 2600)
result = 113.98;
else if(this->getCilindrada() <= 3500)
result = 181.17;
else
result = 320.89;
}
else
{
if(this->getCilindrada() <= 1500)
result = 14.56;
else if(this->getCilindrada() <= 2000)
result = 29.06;
else if(this->getCilindrada() <= 3000)
result = 45.15;
else
result = 113.98;
}
}
else
{
if(this->getCombustivel() == "gasolina")
{
if(this->getCilindrada() <= 1000)
result = 8.10;
else if(this->getCilindrada() <= 1300)
result = 14.56;
else if(this->getCilindrada() <= 1750)
result = 22.65;
else if(this->getCilindrada() <= 2600)
result = 54.89;
else if(this->getCilindrada() <= 3500)
result = 87.13;
else
result = 148.37;
}
else
{
if(this->getCilindrada() <= 1500)
result = 8.10;
else if(this->getCilindrada() <= 2000)
result = 14.56;
else if(this->getCilindrada() <= 3000)
result = 22.65;
else
result = 54.89;
}
}
return result;
}<file_sep>#include "maquinaEmpacotar.h"
#include <sstream>
#include <algorithm>
MaquinaEmpacotar::MaquinaEmpacotar(int capCaixas): capacidadeCaixas(capCaixas)
{}
unsigned MaquinaEmpacotar::numCaixasUsadas() {
return caixas.size();
}
unsigned MaquinaEmpacotar::addCaixa(Caixa& cx) {
caixas.push(cx);
return caixas.size();
}
HEAP_OBJS MaquinaEmpacotar::getObjetos() const {
return this->objetos;
}
HEAP_CAIXAS MaquinaEmpacotar::getCaixas() const {
return this->caixas;
}
unsigned MaquinaEmpacotar::carregaPaletaObjetos(vector<Objeto> &objs)
{
vector<Objeto>::iterator it = objs.begin();
while(it != objs.end())
{
if(it->getPeso() <= this->capacidadeCaixas)
{
this->objetos.push(*it);
it = objs.erase(it);
}
else
it++;
}
return this->objetos.size();
}
Caixa MaquinaEmpacotar::procuraCaixa(Objeto& obj) {
vector<Caixa> temp;
bool found = false;
Caixa cx;
while(!this->caixas.empty())
{
cx = this->caixas.top();
this->caixas.pop();
if(cx.getCargaLivre() >= obj.getPeso())
{
found = true;
break;
}
else
temp.push_back(cx);
}
for(unsigned int i = 0; i < temp.size(); i++)
{
this->caixas.push(temp[i]);
}
if(found == false)
cx = Caixa(capacidadeCaixas);
return cx;
}
unsigned MaquinaEmpacotar::empacotaObjetos() {
while(!this->objetos.empty())
{
Objeto o1 = this->objetos.top();
this->objetos.pop();
Caixa c1 = procuraCaixa(o1);
c1.addObjeto(o1);
this->caixas.push(c1);
}
return this->caixas.size();
}
string MaquinaEmpacotar::imprimeObjetosPorEmpacotar() const {
stringstream result;
if(this->objetos.empty())
result << "Nao ha objetos!" << endl;
else
{
HEAP_OBJS buffer = this->objetos;
while(!buffer.empty())
{
Objeto o1 = buffer.top();
buffer.pop();
result << o1 << endl;
}
}
return result.str();
}
// a alterar
Caixa MaquinaEmpacotar::caixaMaisObjetos() const {
Caixa cx;
HEAP_CAIXAS buffer = this->caixas;
if(buffer.empty())
throw MaquinaSemCaixas();
else
{
cx = buffer.top();
buffer.pop();
while(!buffer.empty())
{
if(cx.getSize() < buffer.top().getSize())
cx = buffer.top()
buffer.pop();
}
}
return cx;
}
<file_sep>#include <iostream>
#include <string>
#include <fstream>
#include "dicionario.h"
#include "bst.h"
using namespace std;
BST<PalavraSignificado> Dicionario::getPalavras() const {
return palavras;
}
bool PalavraSignificado::operator < (const PalavraSignificado &ps1) const {
bool result = false;
if(this->palavra < ps1.palavra)
result = true;
return result;
}
bool PalavraSignificado::operator==(const PalavraSignificado &ps1) const
{
bool result = false;
if(this->palavra == ps1.palavra && this->significado == ps1.significado)
result = true;
return result;
}
ostream& operator <<(ostream &output, PalavraSignificado &ps)
{
output << ps.palavra << endl << ps.significado << endl;
return output;
}
void Dicionario::lerDicionario(ifstream &fich)
{
string palavra, significado;
while(!fich.eof())
{
getline(fich, palavra);
getline(fich, significado);
this->palavras.insert(PalavraSignificado(palavra, significado));
}
return;
}
string Dicionario::consulta(string palavra) const
{
PalavraSignificado p1(palavra, "");
PalavraSignificado px = this->palavras.find(p1);
PalavraSignificado pNotFound("", "");
if(px == pNotFound)
{
BSTItrIn<PalavraSignificado> it(this->palavras);
string palAntes = "", sigAntes = "", palApos = "", sigApos = "";
while(!it.isAtEnd() && it.retrieve() < p1)
{
palAntes = it.retrieve().getPalavra();
sigAntes = it.retrieve().getSignificado();
it.advance();
}
if(!it.isAtEnd())
{
palApos = it.retrieve().getPalavra();
sigApos = it.retrieve().getSignificado();
}
throw PalavraNaoExiste(palAntes, sigAntes, palApos, sigApos);
}
else
return px.getSignificado();
}
//a alterar
bool Dicionario::corrige(string palavra, string significado)
{
bool jaExistia = false;
BSTItrIn<PalavraSignificado> it(this->palavras);
PalavraSignificado pal = this->palavras.find(PalavraSignificado(palavra, ""));
if(pal == PalavraSignificado("", ""))
{
this->palavras.insert(PalavraSignificado(palavra, significado));
}
else
{
this->palavras.remove(PalavraSignificado(palavra, ""));
pal.setSignificado(significado);
this->palavras.insert(pal);
jaExistia = true;
}
return jaExistia;
}
void Dicionario::imprime() const
{
this->palavras.printTree();
return;
}
<file_sep>#include "jogador.h"
void Jogador::adicionaAposta(const Aposta & ap)
{
this->apostas.insert(ap);
}
unsigned Jogador::apostasNoNumero(unsigned num) const
{
unsigned int soma = 0;
tabHAposta::const_iterator it = this->apostas.begin();
for(it; it != this->apostas.end(); it++)
{
if(it->contem(num))
soma++;
}
return soma;
}
tabHAposta Jogador::apostasPremiadas(const tabHInt & sorteio) const
{
tabHAposta money;
money.clear();
tabHAposta::const_iterator it = this->apostas.begin();
for(it; it != apostas.end(); it++)
{
if(it->calculaCertos(sorteio) > 3)
money.insert(*it);
}
return money;
}
<file_sep>#include "disjointSets.h"
DisjointSets::DisjointSets()
{}
// create n disjoint sets (one for each item)
DisjointSets::DisjointSets(int n)
{
for (int i=0 ; i<n; i++)
set.push_back(-1);
}
// Find the root of the set in which element v belongs
int DisjointSets::find(int v) const
{
if (set[v] <0)
return v;
return find(set[v]);
}
// Perform Union of two subsets
void DisjointSets::unionSets(int root1, int root2)
{
set[root2] = root1;
}
int DisjointSets::getNumberOfSets() const
{
int counter = 0;
for(unsigned int i = 0; i < this->set.size(); i++)
{
if(this->set.at(i) == -1)
{
counter++;
}
}
return counter;
}
<file_sep># include <iostream>
# include <stack>
using namespace std;
template <class T>
class StackExt {
private:
stack<T> elemStack;
stack<T> minStack;
public:
StackExt() {};
bool empty() const;
T &top();
void pop();
void push(const T & val);
T &findMin();
};
template <class T>
bool StackExt<T>::empty() const
{
return elemStack.empty() && minStack.empty();
}
template <class T>
T& StackExt<T>::top()
{
T *novo = new T();
if(this->empty())
novo = NULL;
else
novo = &elemStack.top();
return *novo;
}
template <class T>
void StackExt<T>::pop()
{
if(this->empty())
return;
else
{
minStack.pop();
elemStack.pop();
}
}
template <class T>
void StackExt<T>::push(const T & val)
{
if(this->empty())
minStack.push(val);
else if(val < minStack.top())
minStack.push(val);
else
minStack.push(minStack.top());
elemStack.push(val);
}
template <class T>
T& StackExt<T>::findMin()
{
T *novo = new T();
if(this->empty())
novo = NULL;
else
novo = &minStack.top();
return *novo;
}
<file_sep>#include "aposta.h"
#include <iostream>
#include <sstream>
using namespace std;
bool Aposta::contem(unsigned num) const
{
bool result = false;
tabHInt::const_iterator it = this->numeros.find(num);
if(it != this->numeros.end())
result = true;
return result;
}
void Aposta::geraAposta(const vector<unsigned> & valores, unsigned n)
{
this->numeros.clear();
unsigned int i = 0, nValores = 0;
while(nValores < n)
{
pair<tabHInt::iterator, bool> res = this->numeros.insert(valores[i]);
if(res.second == true)
nValores++;
i++;
}
}
unsigned Aposta::calculaCertos(const tabHInt & sorteio) const
{
unsigned int certos = 0;
tabHInt::const_iterator it = sorteio.begin();
for (it; it != sorteio.end(); it++)
{
if(this->contem(*it))
certos++;
}
return certos;
}
//Exercício 2:
unsigned int Aposta::somaNumeros() const
{
unsigned int soma = 0;
tabHInt::const_iterator it = this->numeros.begin();
for(it; it != this->numeros.end(); it++)
{
soma += (*it);
}
return soma;
}
unsigned int Aposta::tamanho() const
{
return this->numeros.size();
}
|
06e9e668d12f0fd6b697ee19509f814690510547
|
[
"Markdown",
"C++",
"CMake"
] | 13 |
Markdown
|
joaoDossena/MIEIC-AEDA
|
06e6ce640d295af44b2ae99ca1f25b6dc7c0f3a3
|
94da6fa656d3f5c9ebce845b28822ce681d87b7c
|
refs/heads/master
|
<repo_name>xyhak47/IVRUnreal_4_13<file_sep>/Source/IVRUnreal_4_13/IVRUnreal_4_13GameMode.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "IVRUnreal_4_13.h"
#include "IVRUnreal_4_13GameMode.h"
<file_sep>/Source/IVRUnreal_4_13/IVRUnreal_4_13.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "IVRUnreal_4_13.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, IVRUnreal_4_13, "IVRUnreal_4_13" );
|
f09ced2c1f9731cb0a0fa28d7661eadd991a9e20
|
[
"C++"
] | 2 |
C++
|
xyhak47/IVRUnreal_4_13
|
55393cb3b6635720973c7bca3a6e7b617f04c056
|
800faadb09bf2ad2e3dc290c2885a9e570229c2a
|
refs/heads/main
|
<file_sep># Training2
Rebase, fork, reset
##### [Nothing about cam here](https://www.youtube.com/watch?v=12rT3uotaqk)
|
b0849958d7054c858680b00425f3a1a5ab475c40
|
[
"Markdown"
] | 1 |
Markdown
|
FlexPartner/Training2
|
6d5aff2e51a69b1cd659782e86967b5d50d25f7a
|
f31ab3dc5dcbc8785faaa407148c7184b54081ae
|
refs/heads/master
|
<file_sep>#include <stdio.h>
int main() {
float base= 5.0f;
float altura= 3.0f;
float area= (base * altura)/2;
printf("%f\n" , area);
return 0;
}<file_sep>#include <stdio.h>
#include<math.h>
int main() {
float a= 1.0f;
float b= 6.0f;
float c= 5.0f;
float delta= (b * b -4 * a * c);
float x1= (-b + sqrt(delta))/(2 * a);
float x2= (-b - sqrt(delta))/(2 * a);
printf("%s%f\n" , "x1= " , x1);
printf("%s%f\n" , "x2= " , x2);
return 0;
}<file_sep>#include <stdio.h>
int main() {
float A1= 5.0f;
float A2= 7.5f;
float media= (0.4 * A1) + (0.6 * A2);
printf("%f\n", media);
return 0;
}<file_sep>#include <stdio.h>
#include <math.h>
int main() {
float angulo= 30.0f;
float distancia= 100.0f;
float PI= 3.1416f;
float angulo_em_graus= (angulo * PI) / 180;
float altura= (distancia * sin(angulo_em_graus));
printf("%f\n" , altura);
return 0;
}
<file_sep>#include <stdio.h>
int main() {
float preco_inicial= 20.0f;
float ICMS= 17.0f/100.0f;
float COFINS= 7.6f/100.0f;
float PISPASEP= 1.65f/100.0f;
float preco_final = ((1 + ICMS + COFINS + PISPASEP) * preco_inicial);
printf("%f\n" , preco_final);
return 0;
}<file_sep>#include <stdio.h>
int main() {
float PI= 3.1416f;
int r= 4.0f;
float perimetro= (2 * PI * r);
printf("%f\n" , perimetro);
return 0;
}<file_sep>#include <stdio.h>
int main() {
int numero= 5673;
int unidade= numero % 10;
int numero1= (numero - unidade) / 10;
int dezena= numero1 % 10;
int numero2= (numero1 - dezena) / 10;
int centena= numero2 % 10;
int numero3= (numero2 - centena) / 10;
int milhar= numero3;
printf("%d%s%d%s%d%s%d%s\n" , unidade , " unidades, " , dezena , " dezenas, " , centena , " centenas e " , milhar , " milhares" );
return 0;
}
<file_sep>#include <stdio.h>
int main() {
float GB= 1024.0f * 1024.0f * 1024.0f;
float valor_qualquer_em_GB= 3.0f ;
float valor_em_bytes= (GB * valor_qualquer_em_GB);
printf("%f%s\n" , valor_em_bytes," Bytes" );
return 0;
}<file_sep>#include <stdio.h>
int main() {
int valor_em_segundos= 100000;
int horas= valor_em_segundos/3600;
int minutos= (valor_em_segundos%3600)/60 ;
int segundos= (valor_em_segundos%3600)%60;
printf("%d%s%d%s%d%s\n" , horas , " horas " , minutos , " minutos " , segundos , " segundos" );
return 0;
}<file_sep>#include <stdio.h>
int main() {
float anos= 18.0f;
float meses= 10.0f;
float dias= 5.0f;
float idade_em_dias= (anos * 365) + (meses * 30) + dias;
printf("%f\n" , idade_em_dias );
return 0;
}
|
af707ae0c0a37e2c347e27bf565f05af2de6e293
|
[
"C"
] | 10 |
C
|
ChristianSPdosS/Pratica-1
|
7b571d07af0c6dd6833052fdfdfc415b39b134ae
|
ed8f8c8da50575cbec5499c07245716657cf62ea
|
refs/heads/master
|
<repo_name>LuluisAngel/WSQ03-Fun-With-Numbers<file_sep>/README.md
# WSQ03-Fun-With-Numbers
Here's the code for that activity:
//<NAME> A01225421
#include <iostream>
using namespace std;
int main(){
int x, y;
cout << "Introduce un numero" << endl;
cin >> x;
cout << "Introduce el segundo numero" << endl;
cin >> y;
cout << "La suma de " << x << " + " << y << " = " << x+y;
/* TODO ESTO SIN COMENTARIOS
En caso de que desees hacer una resta de los numeros ingresados,
solo se necesita cambiar de signo "+" por un "-".
Si deseas hacer una multiplicación solo cambia el signo a "*".
En caso de una division, cambia el signo por una diagonal "/",
y si deseas cambiar el residuo de la division solo cambia el signo por un "%"
*/
return 0;
}
|
757747a8beba1e07fd17eb7e6fbc982fe9a90a5b
|
[
"Markdown"
] | 1 |
Markdown
|
LuluisAngel/WSQ03-Fun-With-Numbers
|
4473b7f628d92e2802e4c49e213fadf7edc24695
|
fbef8f700186731e5fed07313bffcb8b9245c9e4
|
refs/heads/main
|
<repo_name>Rachmawati09/pw2021_203040002<file_sep>/praktikum/tugas4/latihan4c/php/detail.php
<?php
if (!isset($_GET['id'])) {
header("location: ../index.php");
exit;
}
require('functions.php');
$id = $_GET["id"];
$Skincare = query("SELECT * FROM skincare WHERE id = $id")[0];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Skincare</title>
<link rel="stylesheet" type="text/css" href="assets/Semantic-UI-CSS-master/Semantic-UI-CSS-master/semantic.min.css">
<script type="text/javascript" src="semantic.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" />
</head>
<body>
<h2 class="ui segment">Skincare <?= $Skincare["nama_produk"] ?></h2>
<div class="ui container">
<div class="ui card">
<div class="content">
<div class="content">
<a class="header"><?= $Skincare["Kegunaan"] ?></a>
<div class="meta">
<span class="date"><?= $Skincare["Harga"] ?></span>
</div>
<div class="image">
<img src="../assets/img/<?= $Skincare["Gambar"] ?>">
</div>
</div>
</div>
<a href="../index.php"><button class="ui inverted olive button">Back Again</button></a>
</div>
</body>
</html><file_sep>/kuliah/pertemuan6/latihan2.php
<?php
// $mahasiswa = [
// ["<NAME>", "203040002", "<EMAIL>", "Teknik informatika"],
// ["Ferdiansyah", "203030022", "<EMAIL>", "Teknik Mesin" ],
// ["203040039", "depi", "<EMAIL> ", "Teknik Informatika"]
// ];
// Array assosiative
// definisinya sama seperti array numerik, kecuali
// key-nya adalah string yang kita buat sendiri
$mahasiswa = [
[
"Nama" => "<NAME>",
"Nrp" => "203040002",
"Email" => "<EMAIL>",
"Jurusan" => "Teknik Informatika",
"gambar" => "one.jpg"
],
[
"Nama" => "Ferdiansyah",
"Nrp" => "203040022",
"Email" => "<EMAIL>",
"Jurusan" => "Teknik Mesin",
"gambar" => "two.jpg"
],
[
"Nrp" => "203040039",
"Nama" => "Depi",
"Email" => "<EMAIL>",
"Jurusan" => "Teknik Informatika",
"gambar" => "tri.jpg"
]
];
?>
<!DOCTYPE html>
<html>
<head>
<title>Daftar Mahasiswa</title>
</head>
<body>
<h1>Daftar Mahasiswa</h1>
<?php foreach( $mahasiswa as $mhs ):?>
<ul>
<li>
<img src="img/<?= $mhs["gambar"];?>"</li>
<li>Nama : <?= $mhs ["Nama"];?></li>
<li>Nrp : <?= $mhs ["Nrp"];?></li>
<li>Jurusan : <?= $mhs ["Email"];?></li>
<li>Email : <?= $mhs ["Jurusan"];?></li>
</ul>
<?php endforeach; ?>
</body>
</html><file_sep>/praktikum/tugas6/Latihan6b/php/registrasi.php
<?php
require 'functions.php';
if (isset($_POST["register"])) {
if (registrasi($_POST) > 0) {
echo "<script>
alert('Registrasi Berhasil');
document.location.href = 'login.php';
</script>";
} else {
echo "<script>
alert('Registrasi Gagal');
</script>";
}
}
?>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="../css/materialize.min.css" media="screen,projection" />
<link rel="stylesheet" href="css/mantap.css">
<form action="" method="POST" style="margin-left: 25px;">
<table style="margin-left: 50px;">
<tr>
<h2 style="color: turquoise;">Buatlah Username dan Passsword</h2>
</tr>
<tr>
<td><label for="username"><span class="badge bg-success">Username</span></label></td>
<td>:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td><label for="password"><span class="badge bg-success">Password</span></label></td>
<td>:</td>
<td><input type="password" name="password"></td>
</tr>
</table>
<button type="submit" name="register" style="margin-top: 15px;margin-left: 55px;" class="btn btn-primary">REGISTER</button>
<div class="login">
<p style="font-weight: bold;margin-top:15px;">Sudah punya akun ? Login <a href="login.php">Disini</a></p>
</div>
</form><file_sep>/tubes/php/ubah.php
<?php
require 'functions.php';
$id = $_GET['id'];
$Skincare = query("SELECT * FROM skincare WHERE id = $id")[0];
if (isset($_POST['ubah'])) {
if (ubah($_POST) > 0) {
echo "<script>
alert('Data Berhasil Diubah!');
document.location.href = 'admin.php';
</script>";
} else {
echo "<script>
alert('Data Gagal Diubah!');
document.location.href = 'admin.php';
</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ubah Data Produk</title>
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css2?family=Handlee&display=swap" rel="stylesheet">
<link rel="icon" type="image/x-icon" href="../assets/img/shop.png" />
<style type="text/css">
body {
background-image: url(../assets/img/paralak.jpg);
}
.container {
margin: auto;
text-align: center;
background-color: rgb(26, 26, 26);
border-radius: 5px;
box-shadow: 0 4px 12px rgb(0, 0, 0);
width: 420px;
height: 300px;
margin-top: 150px;
padding: 40px;
color: white;
font-family: 'Handlee', cursive;
}
</style>
</head>
<body>
<div class="container">
<h3>Form Ubah Data</h3>
<form action="" method="post">
<input type="hidden" name="id" id="id" value="<?= $Skincare['id']; ?>">
<ul style="list-style: none; ">
<li>
<label for="Gambar" style="text-align:center; margin-left: -110px;">Gambar</label>
: <input type="text" name="Gambar" id="Gambar" require value="<?= $Skincare['Gambar']; ?>"><br><br>
</li>
<li>
<label for="nama_produk" style="margin-left: -130px;">Nama Produk</label>
: <input type="text" name="nama_produk" id="nama_produk" require value="<?= $Skincare['nama_produk']; ?>"><br><br>
</li>
<li>
<label for="Kegunaan" style="text-align: center; margin-left: -120px;">Kegunaan</label>
: <input type="text" name="Kegunaan" id="Kegunaan" require value="<?= $Skincare['Kegunaan']; ?>"><br><br>
</li>
<li>
<label for="Harga" style="margin-left: -130px;">Harga</label>
: <input type="text" name="Harga" id="Harga" require value="<?= $Skincare['Harga']; ?>"><br><br>
</li>
<button type="submit" name="ubah" style="border: none; padding: 5px 10px; background-color: teal; color: white; border-radius: 2px; margin-left: -115px;">Ubah
Data</button>
<button type="submit" style="border: none; padding: 5px 10px; background-color: teal; border-radius: 2px;">
<a href="admin.php" style="text-decoration: none; color: white;">Kembali</a>
</button>
</ul>
</form>
</div>
</body>
</html><file_sep>/tubes/php/detail.php
<?php
if (!isset($_GET['id'])) {
header("Location: ../index.php");
exit;
}
require 'functions.php';
$id = $_GET['id'];
$Skincare = query("SELECT * FROM skincare WHERE id = $id")[0];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Detail Produk</title>
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css2?family=Handlee&display=swap" rel="stylesheet">
<link rel="icon" type="image/x-icon" href="../assets/img/shop.png" />
<style type="text/css">
body {
font-family: 'Handlee', cursive;
background-image: url(../assets/img/paralak.jpg);
}
.container {
margin: auto;
text-align: center;
background-color: rgb(26, 26, 26);
border-radius: 5px;
box-shadow: 0 4px 12px rgb(0, 0, 0);
width: 420px;
height: 500px;
margin-top: 25px;
padding: 50px;
}
.gambar img {
border: 3px solid white;
}
.keterangan {
color: rgb(235, 235, 235);
font-size: 15px;
}
.keterangan :nth-child(1) {
font-size: 25px;
font-weight: 600;
}
</style>
</head>
<body>
<div class="container">
<div class="gambar">
<img width="220px" src="../assets/img/<?= $Skincare["Gambar"]; ?>" alt="">
</div>
<div class="keterangan">
<p><?= $Skincare["nama_produk"]; ?></p>
<p><?= $Skincare["Kegunaan"]; ?></p>
<p><?= $Skincare["Harga"]; ?></p>
</div>
<button class="tombol-kembali"><a href="../index.php">Kembali</a></button>
</div>
</body>
</html><file_sep>/praktikum/tugas4/latihan4b/index.php
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, "pw_tubes_203040002");
$result = mysqli_query($conn, "SELECT * FROM skincare");
?>
<!DOCTYPE html>
<html lang>
<head>
<title>Skincare</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mb-3 mt-3">
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">NO.</th>
<th scope="col">Gambar</th>
<th scope="col">Nama Produk</th>
<th scope="col">Kegunaan</th>
<th scope="col">Harga</th>
</tr>
</thead>
<?php $i = 1; ?>
<?php while ($row = mysqli_fetch_assoc($result)) : ?>
<tr>
<td><b><?= $i ?> </b></td>
<td><img width="220px" src="assets/img/<?= $row["Gambar"]; ?>"></td>
<td><b><?= $row["nama_produk"]; ?></b></td>
<td><b><?= $row["Kegunaan"]; ?></b></td>
<td><b><?= $row["Harga"]; ?></b></td>
</tr>
<?php $i++; ?>
<?php endwhile; ?>
</tr>
</table>
</div>
</body>
</html><file_sep>/kuliah/pertemuan7/latihan1.php
<?php
/*
<NAME>
203040002
github.com/Rachmawati09/pw2021_203040002
pertemuan 7 - 18 maret 2021
Mempelajari mengenai Get & Post
*/
?>
<?php
// $_GET
$mahasiswa = [
[
"Nama" => "<NAME>",
"Nrp" => "203040002",
"Email" => "<EMAIL>",
"Jurusan" => "Teknik Informatika",
"gambar" => "one.jpg"
],
[
"Nama" => "Ferdiansyah",
"Nrp" => "203040022",
"Email" => "<EMAIL>",
"Jurusan" => "Teknik Mesin",
"gambar" => "two.jpg"
]
];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GET</title>
</head>
<body>
<h1>Daftar Mahasiswa</h1>
<ul>
<?php foreach( $mahasiswa as $mhs) : ?>
<li>
<a href="latihan2.php?Nama=<?= $mhs["Nama"]; ?>&Nrp=<?= $mhs["Nrp"]; ?>&Email=<?= $mhs["Email"]; ?>&Jurusan=<?= $mhs["Jurusan"]; ?>&gambar=<?= $mhs["gambar"]; ?>"><?= $mhs["Nama"]; ?></a>
</li>
<?php endforeach; ?>
</ul>
</body>
</html><file_sep>/tubes/php/admin.php
<?php
require 'functions.php';
$Skincare = query("SELECT * FROM skincare");
if (isset($_GET['cari'])) {
$keyword = $_GET['keyword'];
$Skincare = query("SELECT * FROM skincare WHERE
`nama_produk` LIKE '%$keyword%' OR
`Kegunaan` LIKE '%$keyword%' OR
`Harga` LIKE '%$keyword%' ");
} else {
$Skincare = query("SELECT * FROM skincare");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Halaman Admin</title>
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="../css/materialize.min.css" media="screen,projection" />
<link href="https://fonts.googleapis.com/css2?family=Handlee&display=swap" rel="stylesheet">
<link rel="icon" type="image/x-icon" href="../assets/img/shop.png" />
</head>
<body>
<div class="navbar-fixed scrollspy">
<nav class="black">
<div class="container">
<div class="nav-wrapper">
<a href="#!" class="brand-logo" class="darken brown-text text-darken-3" style="margin-right: 15px;">Skincare Shop</a>
<a href="#!" data-target="mobile-nav" class="sidenav-trigger"><i class="material-icons">menu</i></a>
<ul class="right hide-on-med-and-down">
<li><a href="tambah.php" style="font-family: Arial, Helvetica, sans-serif;">Tambah Data</a></li>
<li><a href="logout.php" style="font-family: Arial, Helvetica, sans-serif;">Logout</a></li>
</ul>
</div>
</div>
</nav>
</div>
<!-- sidenav -->
<ul class="sidenav" id="mobile-nav">
<li><a href="tambah.php">Tambah Data</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
<form action="" method="get">
<input type="text" name="keyword" autofocus>
<button type="submit" name="cari" style="border: none; padding: 5px 10px; background-color: teal; color: white; border-radius: 2px;">Cari!</button>
</form>
<div class="container">
<table class="highlight centered">
<thead>
<tr>
<th>No</th>
<th>Opsi</th>
<th>Gambar</th>
<th>Nama Produk</th>
<th>Kegunaan</th>
<th>Harga</th>
</tr>
</thead>
<tbody>
<?php if (empty($Skincare)) : ?>
<tr>
<td colspan="8">
<h3>Produk Tidak Ditemukan</h3>
</td>
</tr>
<?php else : ?>
<?php $i = 1; ?>
<div class="container">
<div class="row">
<div class="col s12">
<?php foreach ($Skincare as $Skin) : ?>
<tr>
<td><?= $i; ?></td>
<td>
<a href="ubah.php?id=<?= $Skin['id'] ?>"><button style="border: none; padding: 5px 13px; background-color: teal; color: white; margin-bottom: 5px; border-radius: 2px;">Ubah</button></a>
<a href="hapus.php?id=<?= $Skin['id']; ?>" onclick="return confirm('Hapus Data??')"><button style="border: none; padding: 5px 10px; background-color: red; color: white; border-radius: 2px;">Hapus</button></a>
</td>
<td><img width="220px" src="../assets/img/<?= $Skin['Gambar']; ?>" alt=""></td>
<td><?= $Skin['nama_produk']; ?></td>
<td><?= $Skin['Kegunaan']; ?></td>
<td><?= $Skin['Harga']; ?></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
<?php endif; ?>
</tbody>
</table>
</div>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html><file_sep>/praktikum/tugas3/latihan3e.php
<?php
$Skincare = [
[
"Nama Produk" => "COSRX Centella Water 150mL",
"Kegunaan" => "Untuk membersihkan kotoran makeup",
"harga" => "Rp.154,600,-",
"gambar" => "corsx water.jpg"
],
[
"Nama Produk" => "COSRX Advance Snail Mucin 96 Power Essence",
"Kegunaan" => "Membuat complexion wajah jadi lebih bersih sekaligus memberikan hidrasi, merevitalisasi dan meningkatkan elastisitas kulit, serta membuat tampilannya menjadi lebih segar",
"harga" => "Rp.155,000,-",
"gambar" => "96 mucin.jpg"
],
[
"Nama Produk" => "COSRX AHA/BHA Clarifying Treatment Toner",
"Kegunaan" => "Membantu Mencegah Timbulnya Komedo. Sumber: Panoxyl. Komedo atau blackheads timbul karena adanya kotoran dan sebum yang terperangkap di dalam pori-pori kulit.",
"harga" => "Rp.105.999,-",
"gambar" => "toner.jpg"
],
[
"Nama Produk" => "<NAME>",
"Kegunaan" => "Melembabkan, Mengurangi Bibir Kering dan Pecah-PecahMelembabkan, Mengurangi Bibir Kering dan Pecah-Pecah",
"harga" => "Rp.29.500,-",
"gambar" => "lipbalm.jpg"
],
[
"Nama Produk" => "<NAME>",
"Kegunaan" => "Membuat bulu matamu lebih bervolume dan lebih lentik",
"harga" => "Rp.85.500,-",
"gambar" => "maskara.jpg"
],
[
"Nama Produk" => "aneige Water Sleeping Mask [15 mL]",
"Kegunaan" => "Membantu kulit mempertahankan kelembaban sepanjang malam, Mengandung komposisi yang menyamankan dan melembutkan kulit saat tidur, Meningkatkan kemampuan kulit untuk beregenerasi",
"harga" => "Rp.27.500,-",
"gambar" => "sleepmask.jpg"
],
[
"Nama Produk" => "COSRX Facial Wash Good Morning Low Ph",
"Kegunaan" => "Membantu Meembersihkan Wajah dari sisa sisa makeup",
"harga" => "Rp.29.900,-",
"gambar" => "face wash.jpg"
],
[
"Nama Produk" => "Masker Organik Greeantea",
"Kegunaan" => "Membantu mencerahkan mata, melembapkan wajah, menghilangkan bekas jerawat",
"harga" => "Rp.15.000,-",
"gambar" => "masker organik.jpg"
],
[
"Nama Produk" => "Cosrx Oil-free Ultra-Moisturizing Lotion (with Birch Sap)",
"Kegunaan" => "Memperbaiki warna, tekstur, dan kulit yang rusak, membuat masalah-masalah kulitmu",
"harga" => "Rp.239.000,-",
"gambar" => "mousturaizer.jpeg"
],
[
"Nama Produk" => "Parfum Tester C HANEL No 5 WOMEN tester",
"Kegunaan" => "Menghasilkan aroma yang mirip dengan madu.",
"harga" => "Rp.395.000,-",
"gambar" => "parfume.jpg"
],
];
?>
<!DOCTYPE html>
<html lang>
<head>
<title>Skincare</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mb-3 mt-3">
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">No.</th>
<th scope="col">Gambar</th>
<th scope="col">Nama Produk</th>
<th scope="col">Kegunaan</th>
<th scope="col">Harga</th>
</tr>
</thead>
<?php $i = 1; ?>
<?php foreach ($Skincare as $skin) : ?>
<tr>
<td><b><?= $i ?> </b></td>
<td><img src="img/<?= $skin["gambar"]; ?>"></td>
<td><b><?= $skin["Nama Produk"]; ?></b></td>
<td><b><?= $skin["Kegunaan"]; ?></b></td>
<td><b><?= $skin["harga"]; ?></b></td>
</tr>
<?php $i++; ?>
<?php endforeach ?>
</tr>
</table>
<tbody>
</div>
</body><file_sep>/praktikum/tugas2/latihan2b.php
<?php
$jawabanIsset = "Isset adalah = untuk memeriksa apakah suatu variabel sudah diatur atau belum <br><br>";
$jawabanEmpty = "Empty adalah = Untuk memeriksa apakah sebuah objek form telah diisi atau tidak";
function soal($style){
echo $GLOBALS['jawabanIsset'];
echo $GLOBALS['jawabanEmpty'];
}
echo soal(
"font-family: Arial; font-size:28px; color:#8c782d; font-style:italic; font-weight: bold;"
);
?><file_sep>/kuliah/pertemuan4/date.php
<?php
/*
<NAME>
203040002
github.com/Rachmawati09/pw2021_203040002
Pertemuan 4 (01 maret 2021)
Materi minggu ini mempelajari mengenai function
*/
?>
<?php
// Date
// untuk menampilkan tanggal dengan format tertentu
// echo date("l, d-M-Y");
// Time
// UNIX Timestamp / EPOCH time
// detik yang sudah berlalu sejak 1 januari 1970
// echo time();
// echo date("l", time()-60*60*24*100);
// mktime
// membuat sendiri detik
// mktime(0,0,0,0,0,0)
// jam, menit, dertik, bulan, tanggal, tahun
// echo date("l", mktime(0,0,0,8,25,1985));
// strtotime
echo date("l", strtotime("25 aug 1985"));
?><file_sep>/praktikum/tugas4/skincare (1).sql
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 03, 2021 at 07:29 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 8.0.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `pw_tubes_203040002`
--
-- --------------------------------------------------------
--
-- Table structure for table `skincare`
--
CREATE TABLE `skincare` (
`id` int(11) NOT NULL,
`Gambar` varchar(100) NOT NULL,
`nama_produk` varchar(100) NOT NULL,
`Kegunaan` varchar(200) NOT NULL,
`Harga` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `skincare`
--
INSERT INTO `skincare` (`id`, `Gambar`, `nama_produk`, `Kegunaan`, `Harga`) VALUES
(3, 'toner.jpg', 'COSRX AHA/BHA Clarifying Treatment Toner', 'Membantu Mencegah Timbulnya Komedo. Sumber: Panoxyl. Komedo atau blackheads timbul karena adanya kotoran dan sebum yang terperangkap di dalam pori-pori kulit.', 'Rp.105.999,-'),
(4, 'lipbalm.jpg', 'Lip Balm Wardah', 'Melembabkan, Mengurangi Bibir Kering dan Pecah-PecahMelembabkan, Mengurangi Bibir Kering dan Pecah-Pecah', 'Rp.29.500,-'),
(5, 'maskara.jpg', 'Maskara Maybelline', 'Membuat bulu matamu lebih bervolume dan lebih lentik', 'Rp.85.500,-'),
(6, 'sleepmask.jpg', 'Laneige Water Sleeping Mask [15 mL]', 'Membantu kulit mempertahankan kelembaban sepanjang malam, Mengandung komposisi yang menyamankan dan melembutkan kulit saat tidur, Meningkatkan kemampuan kulit untuk beregenerasi', 'Rp.27.500,-'),
(8, 'masker organik.jpg', 'Masker Organik', 'Membantu mencerahkan mata, melembapkan wajah, menghilangkan bekas jerawat', 'Rp.15.000,-'),
(9, 'mousturaizer.jpeg', 'Cosrx Oil-free Ultra-Moisturizing Lotion (with Birch Sap)', 'Memperbaiki warna, tekstur, dan kulit yang rusak, membuat masalah-masalah kulitmu', 'Rp.239.000,-'),
(13, '96 mucin.jpg', 'COSRX Advance Snail Mucin 96 Power Essence', 'Membuat complexion wajah jadi lebih bersih sekaligus memberikan hidrasi, merevitalisasi dan meningkatkan elastisitas kulit, serta membuat tampilannya menjadi lebih segar', 'Rp.155,000,-');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `skincare`
--
ALTER TABLE `skincare`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `skincare`
--
ALTER TABLE `skincare`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/README.md
# pw2021_203040002
Repository untuk mata kuliah Pemograman Web 2021
<file_sep>/praktikum/tugas4/latihan4c/index.php
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, "pw_tubes_203040002");
$result = mysqli_query($conn, "SELECT * FROM skincare");
?>
<!DOCTYPE html>
<html lang>
<head>
<title>Skincare</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="grid">
<div class="row">
<?php
foreach ($result as $skin) :
?>
<div class="cell-md-3">
<div class="card">
<div class="card-header">
<td><img width="220px" src="assets/img/<?= $skin['Gambar']; ?>" alt=""></td>
</div>
<div class="card-content p-2">
<a class="text-center" href="php/detail.php?id=<?= $skin["id"] ?>"><?= $skin["nama_produk"] ?> </a>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</body>
</html><file_sep>/kuliah/pertemuan5/latihan3.php
<?php
$mahasiswa = [
["<NAME>", "203040002", "Teknik informatika", "<EMAIL>"],
["Ferdiansyah", "203030022", "Teknik Mesin", "<EMAIL>"],
["Depi", "203040039", "Teknik Informatika", "<EMAIL> "]
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Daftar Mahasiswa</title>
</head>
<body>
<h1>Daftar Mahasiswa</h1>
<?php foreach( $mahasiswa as $mhs ):?>
<ul>
<li>Nama : <?= $mhs [0];?></li>
<li>Nrp : <?= $mhs [1];?></li>
<li>Jurusan : <?= $mhs [2];?></li>
<li>Email : <?= $mhs [3];?></li>
</ul>
<?php endforeach; ?>
</body>
</html><file_sep>/tubes/pw_tubes_203040002 (3).sql
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Waktu pembuatan: 01 Jun 2021 pada 18.17
-- Versi server: 10.4.17-MariaDB
-- Versi PHP: 8.0.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `pw_tubes_203040002`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `skincare`
--
CREATE TABLE `skincare` (
`id` int(11) NOT NULL,
`Gambar` varchar(100) NOT NULL,
`nama_produk` varchar(100) NOT NULL,
`Kegunaan` varchar(200) NOT NULL,
`Harga` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `skincare`
--
INSERT INTO `skincare` (`id`, `Gambar`, `nama_produk`, `Kegunaan`, `Harga`) VALUES
(3, 'foto2.png', 'COSRX AHA/BHA Clarifying Treatment Toner', 'Membantu Mencegah Timbulnya Komedo. Sumber: Panoxyl. Komedo atau blackheads timbul karena adanya kotoran dan sebum yang terperangkap di dalam pori-pori kulit.', 'Rp.105.999,-'),
(4, 'wardah.jpg', 'Lip Balm Wardah', 'Melembabkan, Mengurangi Bibir Kering dan Pecah-PecahMelembabkan, Mengurangi Bibir Kering dan Pecah-Pecah', 'Rp.29.500,-'),
(5, 'Maybelline.jpg', 'Maybelline Hypercurl Mascara', 'Membuat bulu matamu lebih bervolume dan lebih lentik', 'Rp.85.500,-'),
(6, 'foto8.jpeg', 'LANEIGE Lip Sleeping Masks', 'Membantu kulit mempertahankan kelembaban sepanjang malam, Mengandung komposisi yang menyamankan dan melembutkan kulit saat tidur, Meningkatkan kemampuan kulit untuk beregenerasi', 'Rp.27.500,-'),
(8, 'foto6.jpeg', 'Masker Organik', 'Membantu mencerahkan mata, melembapkan wajah, menghilangkan bekas jerawat', 'Rp.15.000,-'),
(9, 'foto5.jpeg', 'Cosrx Oil-free Ultra-Moisturizing Lotion (with Birch Sap)', 'Memperbaiki warna, tekstur, dan kulit yang rusak, membuat masalah-masalah kulitmu', 'Rp.239.000,-'),
(13, 'foto1.jpeg', 'COSRX Advance Snail Mucin 96 Power Essence 100ml', 'Membuat complexion wajah jadi lebih bersih sekaligus memberikan hidrasi, merevitalisasi dan meningkatkan elastisitas kulit, serta membuat tampilannya menjadi lebih segar', 'Rp.155,000,-'),
(14, 'foto3.jpeg', 'COSRX Low pH Good Morning Gel Cleanser', 'pembersih wajah yang digunakan untuk menenangkan, mengeksfoliasi, melembapkan sekaligus membersihkan kulit wajah', 'Rp 12.912'),
(15, 'foto7.jpeg', 'Parfume', 'Wangi. Parfum membantu Moms terhindar dari bau badan dan memastikan Moms harum sepanjang hari.', 'Rp 80.000'),
(16, 'foto4.png', 'Cosrx Centella Water Alcohol-Free Toner', 'Untuk menenangkan kulit yang iritasi karena jerawat/stress, menghidrasi, dan menutrisi kulit dengan vitamin dan mineral.', 'Rp. 157.000');
-- --------------------------------------------------------
--
-- Struktur dari tabel `user`
--
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(64) NOT NULL,
`password` varchar(256) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `user`
--
INSERT INTO `user` (`id`, `username`, `password`) VALUES
(1, 'admin', '<PASSWORD>'),
(2, 'chyntia', <PASSWORD>');
--
-- Indexes for dumped tables
--
--
-- Indeks untuk tabel `skincare`
--
ALTER TABLE `skincare`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT untuk tabel yang dibuang
--
--
-- AUTO_INCREMENT untuk tabel `skincare`
--
ALTER TABLE `skincare`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT untuk tabel `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/tubes/index.php
<?php
require 'php/functions.php';
$Skincare = query("SELECT * FROM skincare");
if (isset($_POST['cari'])) {
$Skincare = cari($_POST['keyword']);
}
?>
<!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection" />
<!-- my css -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--Import Google Font-->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Handlee&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="<KEY>" crossorigin="anonymous" />
<title>Skincare Shop</title>
<link rel="icon" type="image/x-icon" href="assets/img/shop.png" />
</head>
<body id="home" class="scrollspy">
<!-- Navbar -->
<div class="navbar-fixed scrollspy">
<nav class="black">
<div class="nav-wrapper">
<a href="#!" class="brand-logo" class="darken brown-text text-darken-3" style="margin-right: 15px;">Skincare Shop</a>
<a href="#" data-target="mobile-nav" class="sidenav-trigger"><i class="material-icons">menu</i></a>
<ul class="right hide-on-med-and-down">
<li>
<a href="php/login.php" style="font-family: Arial, Helvetica, sans-serif;">Login</a>
</li>
<li>
<a href="php/registrasi.php" style="font-family:Arial, Helvetica, sans-serif;">Sign up</a>
</li>
</ul>
</div>
</nav>
</div>
<!-- Sidenav -->
<ul id="mobile-nav" class="sidenav">
<li>
<div class="user-view">
<div class="background">
<img src="assets/img/sok.jpg">
</div>
<a href="#user"><img class="circle" src="assets/img/tia.jpg"></a>
<a href="#name"><span class="black-text name"><NAME> 203040002</span></a>
<a href="#email"><span class="black-text email"><EMAIL></span></a>
</div>
</li>
<li><a href="http://localhost/pw2021_203040002/"><i class="material-icons">cloud</i>Beranda</a></li>
<li>
<div class="divider"></div>
</li>
<li><a href="php/login.php">Login</a></li>
<li><a href="php/registrasi.php">Sign up</a></li>
</ul>
<a href="#" data-target="mobile-nav" class="sidenav-trigger"><i class="material-icons">menu</i></a>
<!-- Slider -->
<div id="slider" class="slider scrollspy">
<ul class="slides">
<li>
<img src="assets/img/sok.jpg">
<div class="caption left-align">
<h2 class="light brown-text text-darken-3" style="font-family:Arial, Helvetica, sans-serif;">Skincare <br> & Beauty</h2>
<h5 class="light brown-text text-darken-3">It’s never too late to look after yourself. Never too late to eat healthily,<br>get plenty of rest, exercise regularly and look after your skin.</h5>
<a class="waves-effect btn" style="background-color: black;">LEARN MORE</a>
</div>
</li>
</ul>
</div>
<!-- seacrh -->
<h4 class="center"><span class="black-text">Search Produk</span></h4>
<form action="" method="POST">
<input type="text" name="keyword" size="35" placeholder="masukan keyword pencarian.." autocomplete="off" autofocus class="keyword">
<button type="submit" name="cari" class="tombol-cari">Cari!</button>
</form>
<section class="produk">
<section class="skincare-list latest">
<div class="container">
<div class="row">
<div class="col">
<h3 style="text-align: center;">Produk Skincare</h3>
</div>
</div>
<div class="row">
<div class="col s12">
<!-- Database -->
<?php if (empty($Skincare)) : ?>
<tr>
<td colspan="8">
<h3>Produk Tidak Ditemukan</h3>
</td>
</tr>
<?php else : ?>
<div class="row">
<?php foreach ($Skincare as $sk) : ?>
<div class="col s12 m4">
<div class="card small">
<div class="card-image">
<img width="220px" src="assets/img/<?= $sk['Gambar']; ?>" class="responsive-img materialboxed">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4" style="font-size: 20px;"><?= $sk['nama_produk']; ?></span>
</div>
<div class="card-action">
<a class="waves-effect btn-small" style="background-color: black;" href="php/detail.php?id=<?= $sk['id']; ?>">More Detail</a>
</div>
</div>
</div>
<?php endforeach ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</section>
</div>
</div>
</section>
<!-- Footer -->
<footer class="black lighten-1">
<div class="container">
<div class="row">
<div class="col l6 s12">
<h5 class="white-text">SKINCARE SHOP</h5>
<p class="grey-text text-lighten-4">Perawatan kulit adalah rangkaian dari berbagai penerapan yang mendukung keadaan integritas kulit, untuk meningkatkan sebuah penampilan dan mengubah kondisi kulit. Mereka dapat mengandung nutrisi, menghindari dari paparan sinar matahari yang berlebihan dan penggunaan produk kulit emolien yang tepat.</p>
</div>
<div class="col l4 offset-l2 s12">
<h5 class="white-text">Follow Social Media</h5>
<div class="icon-sosmed">
<a href="https://twitter.com/aprrach" class="white-text" style="margin-right: 10px;">
<i class="fab fa-twitter fa-4x"></i>
</a>
<a href="https://instagram.com/chyntiacitra" class="white-text" style="margin-right: 10px;">
<i class="fab fa-instagram fa-4x"></i>
</a>
<a href="https://facebook.com/sintia666" class="white-text" style="margin-right: 10px;">
<i class="fab fa-facebook fa-4x"></i>
</a>
</div>
</div>
</div>
</div>
<div class="white-text">
<div class="container">
Copyright © 2021 <NAME>
</div>
</div>
</footer>
<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="js/materialize.min.js"></script>
<script src="js/script.js"></script>
</body>
<script type="text/javascript">
const sideNav = document.querySelectorAll('.sidenav');
M.Sidenav.init(sideNav);
const slider = document.querySelectorAll('.slider');
M.Slider.init(slider, {
indicators: false,
height: 500,
transition: 600,
interval: 3000
});
const materialbox = document.querySelectorAll('.materialboxed');
M.Materialbox.init(materialbox);
const scroll = document.querySelectorAll('.scrollspy');
M.ScrollSpy.init(scroll, {
scrolloffset: 50
});
</script>
</html><file_sep>/kuliah/pertemuan2/index.php
<?php
/*
<NAME>
203040002
github.com/Rachmawati09/pw2021_203040002
pertemuan 2 - 8 februari 2021
Mempelajari mengenai sintaks PHP
*/
?>
<?php
// Standar Ouput
// echo, prints
// print_r
// var-dumb
// Penulisan sintaks PHP
// 1.PHP didalam HTML
// 2.HTML didalam PHP
// Variabel dan Tipe Data
// Varibel
// tidak boleh diawali dengan angka, tapi boleh mengandung angka
// $Nama = "<NAME>";
// echo'Hallo, Nama Saya $Nama';
// Operator
// aritmatika
// + - * / %
// $x= 10;
// $y= 20;
// echo $x * $y;
// penggabung string / concatenation / concat
// .
// $Nama_Depan = "Chyntia";
// $Nama_Belakang = "Citra";
// echo $Nama_Depan . " " . $Nama_Belakang;
// Assignment
// =, +=, -=, *=, /=, %=, .=
// $x = 1;
// $x -=5;
// echo $x;
// $Nama = "Chyntia";
// $Nama.= "";
// $Nama.= "Citra";
// echo $Nama;
// Perbandingan
// <, >, <=, >=, ==, !=
// var_dump(1 == "1");
// Identitas
// ===, !==
// var_dump(1 === "1");
// Logika
// &&, ||, !
// $x = 30;
// var_dump($x < 20 || $x % 2 ==0);
?><file_sep>/tubes/ajax/ajax_cari.php
<?php
require "../php/functions.php";
$Skincare = cari($_GET['keyword']);
?>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>No</th>
<th>Gambar</th>
<th>Nama Produk</th>
<th>More</th>
</tr>
<?php if (empty($Skincare)) : ?>
<tr>
<td colspan="4">
<p style="color: red; font-style: italic;">Produk Skincare tidak ditemukan!</p>
</td>
</tr>
<?php endif; ?>
<?php $i = 1;
foreach ($Skincare as $sk) : ?>
<tr>
<td><?= $i++; ?></td>
<td><img src="assets/img/<?= $sk['Gambar']; ?>" width="60"></td>
<td><?= $sk['nama_produk']; ?></td>
<td>
<a href="php/detail.php?id=<?= $sk['id']; ?>">More Detail</a>
</td>
</tr>
<?php endforeach; ?>
</table><file_sep>/praktikum/tugas1/latihan1a.php
<?php
for($i =1; $i <= 3; $i++) {
for($j =1; $j <= 3; $j++) {
echo "ini pengulangan ke ($i, $j) <br>";
}
}
?>
|
78f0a63b4bffd7d3051287eecd30d4e8a1f09900
|
[
"Markdown",
"SQL",
"PHP"
] | 20 |
Markdown
|
Rachmawati09/pw2021_203040002
|
968facbb743dcdcb08cc262ec2d320f935251ff7
|
9c70c062dc904af1385f5cf368f8c5f228750003
|
refs/heads/main
|
<repo_name>trinh064/hw7-trinh064<file_sep>/dbConnect.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
var mysql = require('mysql');
var fs = require('fs');
var parser = require('xml2json');
fs.readFile( './dbconfig.xml', function(err, data) {
var json = JSON.parse(parser.toJson(data, {reversible: true}))['dbconfig'];
console.log(JSON.stringify(json));
con=mysql.createPool({
connectionLimit: json.connectionlimit.$t,
host: json.host.$t,
user: json.user.$t, // replace with the database user provided to you
password: <PASSWORD>, // replace with the database password provided to you
database: json.database.$t, // replace with the database user provided to you
port: json.port.$t
});
});
// TODO: Add implementation for other necessary end-points
module.exports = router;
<file_sep>/README.md
# Full stack web application
uname: admin$ <br>
pass: <PASSWORD>% <br>
Add, remove, edit contacts from the SQL database, get stock data from API
|
2e9ef1b4aa24e1f77c6c818c78750d19c6a99095
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
trinh064/hw7-trinh064
|
3e888583c24cfbeed958e0fcbba9c013fb0f3f26
|
45a551992a84b37522981152368e7cab39aa0329
|
refs/heads/main
|
<repo_name>DWoldan/dwoldanBootStrap.github.io<file_sep>/README.md
# dwoldanBootStrap.github.io
Website based on BootStrap 4.5
|
6ff9118a62b93ed636cc00956945207cf6610547
|
[
"Markdown"
] | 1 |
Markdown
|
DWoldan/dwoldanBootStrap.github.io
|
931a1732861a70e6032ba716f9e77946417a55b4
|
79a66e6cb3a056a83b7051419a3602cfcf2267a1
|
refs/heads/master
|
<repo_name>andri95/NF-Lokaverkefni<file_sep>/leikur.py
# coding: latin-1
# If you are commenting in icelandic you need the line above.
import pygame
import random
class Asteroid(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = asteroid_image
self.rect = self.image.get_rect()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = player_image
self.rect = self.image.get_rect()
class Missile(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = missile_image
self.rect = self.image.get_rect()
# myndir
player_image = pygame.image.load('myndir/spilamadur.png')
asteroid_image = pygame.image.load('myndir/bolti.png')
missile_image = pygame.image.load('myndir/missile.png')
bg = pygame.image.load('myndir/background.jpg')
WHITE = (255, 255, 255)
pygame.init()
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
# sprite og groups.
asteroid_list = pygame.sprite.Group()
# Group to hold missiles
missile_list = pygame.sprite.Group()
# This is a list of every sprite.
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
for i in range(4):
for column in range(8):
block = Asteroid() # Set a random location for the block
block.rect.x = 150 + (column * 50) # random.randrange(screen_width - 20)
block.rect.y = 35 + (
i * 45) # random.randrange(screen_height - 160) # ekki l�ta asteroid-ana byrja of ne�arlega
asteroid_list.add(block)
all_sprites_list.add(block)
# Create a player block
player = Player()
player.rect.x = 320
player.rect.y = 380
all_sprites_list.add(player)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
score = 0
speed = 1
# -------- Main Program Loop -----------
# We need to check out what happens when the player hits the space bar in order to "shoot".
# A new missile is created and gets it's initial position in the "middle" of the player.
# Then this missile is added to the missile sprite-group and also to the all_sprites group.
flags = False
while not done:
screen.blit(bg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
shot = Missile()
shot.rect.x = player.rect.x + 30
shot.rect.y = player.rect.y - 15
missile_list.add(shot)
all_sprites_list.add(shot)
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
if player.rect.x < -60:
player.rect.x = 700
player.rect.x -= 5
elif key[pygame.K_RIGHT]:
if player.rect.x > 700:
player.rect.x = - 60
player.rect.x += 5
# Below is another good example of Sprite and SpriteGroup functionality.
# It is now enough to see if some missile has collided with some asteroid
# and if so, they are removed from their respective groups.l
# In other words: A missile exploded and so did an asteroid.
# See if the player block has collided with anything.
pygame.sprite.groupcollide(missile_list, asteroid_list, True, True)
# Missiles move at a constant speed up the screen, towards the enemy
for shot in missile_list:
shot.rect.y -= 5
# All the enemies move down the screen at a constant speed
for block in asteroid_list:
if block.rect.x >= 680:
speed = -2
flags = True
if block.rect.x <= 0:
speed = 2
if flags:
for x in range(len(asteroid_list)):
asteroid_list.sprites()[x].rect.y += 6
for y in range(len(asteroid_list)):
asteroid_list.sprites()[x].rect.y += 6
flags = False
block.rect.x += speed
# print(block.rect.x)
# Draw all the spites
all_sprites_list.draw(screen)
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
|
b2e2ed508ca2df369bfaa8696709902078bd2432
|
[
"Python"
] | 1 |
Python
|
andri95/NF-Lokaverkefni
|
560ecd5f096d629dedd667c5c021f97aab74e0fb
|
485ba0c70590fc96ae03210e3550f56d97b6075a
|
refs/heads/master
|
<repo_name>rutrader/nette-blog<file_sep>/app/presenters/Blog/BasePresenter.php
<?php
/**
* Created by PhpStorm.
* User: rutrader
* Date: 9/27/2015
* Time: 11:22 PM
*/
namespace app\presenters\Blog;
use app\misc\AngularMacro;
use Kdyby\Doctrine\EntityManager;
use Nette\Application\UI\Presenter;
use Nette\Bridges\ApplicationLatte\Template;
use Nette\Caching\Storages\MemcachedStorage;
use Nette\Database\Context;
use Nette\DI\Container;
abstract class BasePresenter extends Presenter {
/**
* @var Context
*/
protected $context;
/**
* @var Container
*/
protected $container;
/**
* @var EntityManager
*/
protected $em;
/**
* @var MemcachedStorage $cache
*/
protected $cache;
public function __construct( Context $context, Container $container, EntityManager $entityManager ) {
$this->context = $context;
$this->container = $container;
$this->em = $entityManager;
$this->cache = $this->container->getService('cacheStorage');
}
public function renderShow($id) {}
/**
* @param Template $template
*/
public function templatePrepareFilters($template) {
AngularMacro::install($template->getLatte()->getCompiler());
}
}<file_sep>/app/presenters/PostPresenter.php
<?php
/**
* Created by PhpStorm.
* User: rutrader
* Date: 9/27/2015
* Time: 11:20 PM
*/
namespace App\Presenters;
use app\presenters\Blog\BasePresenter;
use Nette;
use App\Posts;
class PostPresenter extends BasePresenter {
/**
*
*/
public function actionIndex() {}
/**
*
*/
public function actionList() {
$db = $this->em->getRepository(Posts::getClassName());
// $this->cache->remove($this->action.'-posts-cache');
$arPosts = $this->cache->read($this->action.'-posts-cache');
if( !$arPosts ) {
$oPosts = $db->findAll();
foreach( $oPosts as $post ) {
$arPosts[] = [
'id' => $post->id,
'title' => $post->title,
'intro' => $post->intro,
'content' => $post->content,
'date' => $post->createdAt->format('Y-m-d'),
'cover' => $post->postCover,
];
}
$this->cache->write($this->action.'-posts-cache', $arPosts, []);
}
$this->payload->posts = $arPosts;
$this->sendResponse( new Nette\Application\Responses\JsonResponse($this->payload));
}
/**
* @param $id
*/
public function actionView($id) {
$repo = $this->em->getRepository(Posts::getClassName());
$post = $this->cache->read($this->action.'-post-cache');
if( !$post ) {
$post = $repo->find($id);
$this->cache->write($this->action.'-post-cache', $post, [] );
}
$this->payload->user_loggedin = $this->getUser()->isLoggedIn();
$this->payload->post = [
'id' => $post->id,
'title' => $post->title,
'intro' => $post->intro . "<br/><br />",
'content' => $post->content,
'date' => $post->createdAt->format('Y-m-d'),
'cover' => $post->postCover,
];
$this->sendResponse( new Nette\Application\Responses\JsonResponse($this->payload));
}
public function actionEdit($id) {
if (!$this->getUser()->isLoggedIn()) {
// $this->redirect('Sign:in');
}
$repo = $this->em->getRepository(Posts::getClassName());
$post = $repo->find($id);
if (!$post) {
$this->error('Post not found');
}
$this->payload->post = [
'id' => $post->id,
'title' => $post->title,
'intro' => $post->intro,
'content' => $post->content,
'date' => $post->createdAt->format('Y-m-d'),
'cover' => $post->postCover,
];
$this->sendResponse( new Nette\Application\Responses\JsonResponse($this->payload) );
// $this['postForm']->setDefaults($post->toArray());
}
public function actionSave() {
$repo = $this->em->getRepository(Posts::getClassName());
$oPost = $repo->find($this->request->getPost('id'));
if( is_null( $oPost ) ) {
$oPost = new Posts();
}
$oPost->title = $this->request->getPost('title');
$oPost->content = $this->request->getPost('content');
$oPost->intro = strip_tags($this->request->getPost('intro'));
$oPost->createdAt = $this->request->getPost('created_at') . " 00:00:00";
$postCover = $this->savePostCover();
if( $postCover ) {
$oPost->postCover = $postCover;
}
$this->em->persist($oPost);
$this->em->flush();
$this->flashMessage('Thank you for your comment', 'success');
$this->redirectUrl('/#/post/'.$oPost->id);
}
public function actionCreate() {
/*if (!$this->getUser()->isLoggedIn()) {
$this->redirect('Sign:in');
}*/
$this->sendResponse( new Nette\Application\Responses\JsonResponse([]) );
}
/*public function renderShow( $postID ) {
$post = $this->context->table('posts')->get($postID);
if( !$post ) {
$this->error('Post not found');
}
$this->template->post = $post;
$this->template->comments = $post->related('comments')->order('created_at');
}*/
public function createComponentCommentForm() {
/*$form = new Nette\Application\UI\Form();
$form->addText('name', 'Your name:' )
->setRequired(true)
->setAttribute('class', 'input-sm col-md-12');
;
$form->addText('email', 'Email:')
->setAttribute('class', 'input-sm col-md-12')
;
$form->addTextArea('content', 'Comment:')
->setAttribute('class', 'itextarea')
->setRequired();
$form->addText('age', 'Age:')
->setType('number')
->addRule(Form::INTEGER, 'Your age must be an integer.')
->addRule(Form::RANGE, 'You must be older %d years and be under %d.', array(18, 120));
$form->addSubmit('send', 'Publish comment');
$form->onSuccess[] = array($this, 'commentFormSucceeded');
$form->onSubmit[] = array($this, 'commentFormError');
return $form;*/
}
public function commentFormSucceeded( $form, $values) {
/*$postId = $this->getParameter('postID');
$this->context->table('comments')->insert(array(
'post_id' => $postId,
'name' => $values->name,
'email' => $values->email,
'content' => $values->content,
));
$this->flashMessage('Thank you for your comment', 'success');
$this->redirect('this');*/
}
public function createComponentPostForm() {
/*$form = new Form;
$form->addText('title', 'Title:')
->setRequired();
$form->addTextArea('content', 'Content:')
->setRequired();
$form->addSubmit('send', 'Save and publish');
$form->onSuccess[] = array($this, 'postFormSucceeded');
return $form;*/
}
public function postFormSucceeded($form, $values) {
/*if (!$this->getUser()->isLoggedIn()) {
$this->error('You need to log in to create or edit posts');
}
$postId = $this->getParameter('postId');
if ($postId) {
$post = $this->context->table('posts')->get($postId);
$post->update($values);
} else {
$post = $this->context->table('posts')->insert($values);
}
$this->flashMessage('Post was published', 'success');
$this->redirect('show', $post->id);*/
}
/**
* @return bool|string
*/
public function savePostCover() {
if ( !empty( $_FILES ) && strlen($_FILES['cover']['name'] ) > 0 ) {
$tempPath = $_FILES['cover']['tmp_name'];
$dirPath = $this->container->parameters['wwwDir'] . DIRECTORY_SEPARATOR . $this->container->parameters['image_path'];
$arFile = explode( '.', $_FILES['cover']['name']);
$fileName = md5($arFile[0]).'.'.$arFile[1];
$uploadPath = $dirPath . DIRECTORY_SEPARATOR . 'portfolio' . DIRECTORY_SEPARATOR . $fileName;
move_uploaded_file( $tempPath, $uploadPath );
return $fileName;
} else {
return false;
}
}
}<file_sep>/app/presenters/HomepagePresenter.php
<?php
namespace App\Presenters;
use app\presenters\Blog\BasePresenter;
use Nette;
class HomepagePresenter extends BasePresenter
{
public function renderDefault() {
// $this->template->posts = $this->context->table('posts')
// ->order('created_at DESC')
// ->limit(5);
}
}
<file_sep>/app/presenters/templates/Post/index.latte
{block content}
{/block content}<file_sep>/www/js/app.js
/**
* Created by rishemgulov on 16.10.2015.
*/
'use strict';
/* App Module */
var blogApp = angular.module('blogApp', [
'postControllers',
'ngRoute',
'ngSanitize',
'angularFileUpload'
]);
blogApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/list.html',
controller: 'PostsListCtrl'
}).
when('/create', {
templateUrl: 'partials/post-create.html'
//controller: 'PostCreateCtrl'
}).
when('/post/:postId', {
templateUrl: 'partials/post-detail.html',
controller: 'PostDetailCtrl'
}).
when('/post/edit/:postId', {
templateUrl: 'partials/post-edit.html',
controller: 'PostEditCtrl'
}).
when('/sign/in', {
templateUrl: 'partials/sign-in.html'
//controller: 'SignInCtrl'
}).
when('/sign/out', {
templateUrl: 'partials/empty.html',
controller: 'SignOutCtrl'
})
.otherwise({
redirectTo: 'error.html'
});
}]);
blogApp.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
<file_sep>/app/presenters/templates/@layout.latte
<!DOCTYPE html>
<html ng-app="blogApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>{ifset title}{include title|striptags} | {/ifset}Nette Web</title>
<link rel="shortcut icon" href="{$basePath}/favicon.ico">
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" >
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css" >
<link rel="stylesheet" href="/bower_components/animate.css/animate.min.css" >
<link rel="stylesheet" href="/css/set.css" >
<link rel="stylesheet" href="/css/main.css" >
{block stylesheets}{/block}
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="/bower_components/angular/angular.min.js"></script>
<script src="/bower_components/angular-touch/angular-touch.min.js"></script>
<script src="/bower_components/angular-route/angular-route.min.js"></script>
<script src="/bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script src="/bower_components/angular-file-upload/dist/angular-file-upload.min.js"></script>
<script src="/bower_components/wow/dist/wow.min.js"></script>
<script src="/bower_components/jquery-touchswipe/jquery.touchSwipe.min.js"></script>
<script src="/bower_components/respond/dest/respond.min.js"></script>
<script src="/js/app.js"></script>
<script src="/js/controllers.js"></script>
<script src="/js/directives.js"></script>
<script src="/js/main.js"></script>
</head>
<body>
<div class="topbar animated fadeInLeftBig"></div>
<div class="navbar-wrapper">
<div class="container">
<div id="top-nav" role="navigation" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<!-- Logo Starts -->
<a href="/#/" class="navbar-brand"><img alt="logo" src="images/logo.png"></a>
<!-- #Logo Ends -->
<button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Nav Starts -->
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right scroll">
<li class="active"><a href="/#/">Home</a></li>
{if !$user->loggedIn}
<li><a href="/#/sign/in">Sign in</a></li>
{else}
<li><a href="/#/sign/out">Sign out</a></li>
{/if}
{if $user->loggedIn}
<li><a href="/#/create">Create post</a></li>
{/if}
</ul>
</div>
<!-- #Nav Ends -->
</div>
</div>
</div>
</div>
<div class="row" ng-view>
</div>
</body>
</html>
<file_sep>/app/presenters/SignPresenter.php
<?php
/**
* Created by PhpStorm.
* User: rutrader
* Date: 10/6/2015
* Time: 12:11 AM
*/
namespace App\Presenters;
use app\presenters\Blog\BasePresenter;
use Nette\Application\Responses\JsonResponse;
use Nette\Application\UI\Form;
use Nette\Security\AuthenticationException;
class SignPresenter extends BasePresenter {
public function actionIn() {
}
public function actionOut() {
$this->getUser()->logout();
$this->sendResponse( new JsonResponse(['message' => 'You have been signed out.']) );
}
public function actionAuth() {
$values = $this->request->getPost();
try {
$this->getUser()->login( $values['_username'], $values['_password'] );
$this->redirectUrl( '/' );
} catch ( AuthenticationException $e ) {
exit;
}
}
/*protected function createComponentSignInForm() {
$form = new Form();
$form->getElementPrototype()->class('form-signin');
$form->addText('username', 'Username:')
->setAttribute('class', 'form-control')
->setRequired('Please enter your username.')
->getLabelPrototype()->class('sr-only')
;
$form->addPassword('password', '<PASSWORD>:')
->setAttribute('class', 'form-control')
->setRequired('Please enter your password.')
->getLabelPrototype()->class('sr-only')
;
// $form->addCheckbox('remember', 'Keep me signed in');
$form->addSubmit('send', 'Sign in')
->setAttribute('class', 'btn btn-lg btn-primary btn-block')
;
$form->onSuccess[] = array($this, 'signInFormSucceeded');
$renderer = $form->getRenderer();
// echo "<pre>"; var_dump( $renderer ); echo "</pre>";
// die();
$renderer->wrappers['form']['container'] = '';
$renderer->wrappers['controls']['container'] = NULL;
$renderer->wrappers['pair']['container'] = '';
$renderer->wrappers['pair']['.error'] = '';
$renderer->wrappers['control']['container'] = '';
$renderer->wrappers['label']['container'] = '';
$renderer->wrappers['control']['description'] = '';
$renderer->wrappers['control']['errorcontainer'] = '';
$form->setRenderer($renderer);
return $form;
}
public function signInFormSucceeded($form) {
$values = $form->values;
try {
$this->getUser()->login($values->username, $values->password);
$this->redirect('Homepage:');
} catch (AuthenticationException $e) {
$form->addError('Incorrect username or password.');
}
}
*/
}<file_sep>/app/config/config.neon
# WARNING: it is CRITICAL that this file & directory are NOT accessible directly via a web browser!
# http://nette.org/security-warning
parameters:
image_path: 'images'
php:
date.timezone: Europe/Prague
application:
errorPresenter: Error
mapping:
*: App\*Module\Presenters\*Presenter
session:
expiration: 14 days
services:
router: App\RouterFactory::createRouter
cacheStorage: Nette\Caching\Storages\MemcachedStorage
extensions:
# add theese four lines
console: Kdyby\Console\DI\ConsoleExtension
events: Kdyby\Events\DI\EventsExtension
annotations: Kdyby\Annotations\DI\AnnotationsExtension
doctrine: Kdyby\Doctrine\DI\OrmExtension
doctrine:
user: doctrine
password: '***'
dbname: doctrine_online
metadata:
App: %appDir%
metadataCache: Kdyby\DoctrineCache\MemcacheCache(@cacheStorage::getConnection())
security:
users:
admin:
password: <PASSWORD>
roles: [administrator]
roles:
guest:
authenticated: guest
administrator: authenticated
nette:
latte:
macros:
- app\misc\AngularMacro::install<file_sep>/app/presenters/templates/Homepage/default.latte
{* This is the welcome page, you can delete it *}
{block content}
{* <div class="col-sm-8 blog-main">
<div n:foreach="$posts as $post" class="blog-post">
<h2><a href="{link Post:show $post->id}" class="blog-post-title">{$post->title}</a></h2>
<p class="blog-post-meta">{$post->created_at|date:'F j, Y'}</p>
<div>
<p>{$post->content|noescape}</p>
</div>
</div>
</div>
<div class="col-sm-3 col-sm-offset-1 blog-sidebar">
<div class="sidebar-module sidebar-module-inset">
<h4>About</h4>
<p>Etiam porta <em>sem malesuada magna</em> mollis euismod. Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur.</p>
</div>
<div class="sidebar-module">
<h4>Archives</h4>
<ol class="list-unstyled">
<li n:foreach="[1,2,3,4] as $year"><a href="#">0{$year}-{2012+$year}</a></li>
</ol>
</div>
<div class="sidebar-module">
<h4>Elsewhere</h4>
<ol class="list-unstyled">
<li><a href="#">GitHub</a></li>
<li><a href="#">Twitter</a></li>
<li><a href="#">Facebook</a></li>
</ol>
</div>
</div>
{/block}*}
<div class="row">
<div class="span4">
<h2>Default</h2>
<p>This is a Homepage view.</p>
</div>
</div>
{/block}<file_sep>/app/model/Posts.php
<?php
/**
* Created by PhpStorm.
* User: rishemgulov
* Date: 21.10.2015
* Time: 17:33
*/
namespace App;
use Kdyby\Doctrine\Entities\BaseEntity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Posts
* @ORM\Entity()
* @package App
*/
class Posts extends BaseEntity{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\Column(type="string", name="title")
*/
protected $title;
/**
* @ORM\Column(type="string", name="intro")
*/
protected $intro;
/**
* @ORM\Column(type="string", name="content")
*/
protected $content;
/**
* @ORM\Column(type="datetime", name="created_at", options={"format":"Y-m-d"})
*/
protected $createdAt;
/**
* @ORM\Column(type="string", name="post_cover")
*/
protected $postCover;
public function getCreatedAt() {
return $this->createdAt;
}
public function setCreatedAt($created_at) {
if( !$created_at || !isset($created_at) || strlen($created_at) <= 0 ) {
$created_at = 'now';
}
$this->createdAt = new \DateTime($created_at);
}
}<file_sep>/app/misc/AngularMacro.php
<?php
/**
* Created by PhpStorm.
* User: rutrader
* Date: 10/15/2015
* Time: 10:54 PM
*/
namespace app\misc;
use Latte\Compiler;
use Latte\Engine;
use Latte\MacroNode;
use Latte\Macros\MacroSet;
use Latte\PhpWriter;
use Nette\Bridges\ApplicationLatte\Template;
class AngularMacro extends MacroSet {
/**
* @param $compiler
*/
public static function install(Compiler $compiler) {
$me = new static($compiler);
$me->addMacro('ng', array($me, 'macroNg'), array($me, 'macroEndNg'));
}
public function macroNg(MacroNode $node, PhpWriter $writer) {
$name = $node->tokenizer->fetchWord();
return $writer->write("echo '{{'.{$writer->formatWord($name)}");
}
public function macroEndNg(MacroNode $node, PhpWriter $writer) {
return $writer->write("echo '}}'");
}
}<file_sep>/README.md
### Blog example with angularJS
##1.0##
##1.1##
##1.5##
> npm install
> ./node_modules/.bin/webdriver-manager update
## Run tests ##
> ./node_modules/.bin/protractor test/protractor-conf.js
|
348c16f7201b4ba1f217f01af5ddd75ae2b32c11
|
[
"NEON",
"Markdown",
"JavaScript",
"PHP",
"Latte"
] | 12 |
NEON
|
rutrader/nette-blog
|
bdbc445d1be4e8127e1a71fe9e01219eba760847
|
0ce999bec95d36f39f267e72a698dfa1b7f59497
|
refs/heads/master
|
<file_sep>#include "libmx.h"
static void get_word(int *i, char **arr_is, char *tmp);
char **mx_get_arr_islands(int G, char **strarr){
int i = 0;
char **arr_is = (char **) malloc((G + 1) * sizeof(char *));
for (int j = 1; strarr[j] ; j++) {
char **tmp = mx_pf_split(strarr[j]);
get_word(&i, arr_is, tmp[0]);
get_word(&i, arr_is, tmp[1]);
mx_del_strarr(&tmp);
}
if (i != G) {
mx_printerr("error: invalid number of islands\n");
exit(1);
}
arr_is[i] = NULL;
return arr_is;
}
static void get_word(int *i, char **arr_is, char *tmp) {
int flag = 0;
for (int k = 0; arr_is[k] && k < *i; k++) {
if (mx_strcmp(arr_is[k], tmp) == 0){
flag += 1;
}
}
if (flag == 0) {
arr_is[*i] = mx_strdup(tmp);
*i += 1;
}
}
<file_sep>#include "libmx.h"
int mx_count_substr(const char *str, const char *sub) {
if (!str || !sub) return -1;
char *s = (char *)str;
int ln = mx_strlen(sub);
int k = 0;
while (*s) {
for (int i = 0; i < ln && s[i] == sub[i]; i++) {
if (sub[i + 1] == '\0') {
k++;
}
}
s++;
}
return k;
}
<file_sep>#include "libmx.h"
int mx_count_words(const char *str, char c) {
if (!str) return -1; // в пдф повинно вертати нічого?????
int s = 0;
while (*str != '\0') {
// if not word
if (*str == c)
while (*str == c && *str != '\0')
str++;
// if word
if (*str != c && *str != '\0') {
s++;
while (*str != c && *str != '\0')
str++;
}
}
return s;
}
<file_sep>#include "libmx.h"
void mx_printlist(t_list *list) {
t_list *q = list;
while (q->next != NULL) {
mx_printstr(q->data);
mx_printstr(" ");
q = q->next;
}
mx_printstr(q->data);
}
<file_sep>#include "libmx.h"
unsigned long mx_hex_to_nbr(const char *hex) {
unsigned long n = 0;
unsigned long t = 1;
unsigned long m = 1;
int k = 0;
// check
if (!hex || *hex == 0) {
return n;
}
// all ok
const char *tmp = hex;
// found k (count chars in hex) and m (multiply on 16)
while (*tmp != '\0') {
k++;
tmp++;
m *= 16;
}
for (int i = 0; i < k; i++) {
if (hex[i] >= '0' && hex[i] <= '9') {
t = hex[i] - '0';
}
else if (hex[i] >= 'a' && hex[i] <= 'f') {
t = hex[i] - 'a' + 10;
}
else if (hex[i] >= 'A' && hex[i] <= 'F') {
t = hex[i] - 'A' + 10;
}
else {
return 0;
}
m /= 16;
n += t * m;
}
return n;
}
<file_sep>#include "libmx.h"
static void printerr_line(int i);
static void empty_lines(char *strarr);
static void INVLD_LINE_ASCII(char **strarr);
static void INVLD_LINE_INPUT(char **strarr);
static void INVLD_LINE1_DIGIT(char *strarr);
static void INVLD_FILE(int c, char *v[]);
void mx_pf_errors(int c, char *v[]) {
INVLD_FILE(c, v); // chech file
char *str = mx_file_to_str(v[1]);
empty_lines(str);
char **strarr = mx_strsplit(str, '\n');
INVLD_LINE1_DIGIT(strarr[0]); // chech if line1 is digit
INVLD_LINE_INPUT(strarr); // chech if line is correct '-' ','
INVLD_LINE_ASCII(strarr); // chech if line is correct ascii
mx_strdel(&str); // clean all leaks
mx_del_strarr(&strarr);
}
static void empty_lines(char *str) { //заодно рахує кількість островів
int k = 0;
for (int i = 0; i < mx_strlen(str) - 1; i++) {
if (str[i] == '\n') {
k++;
if (str[i] == str[i + 1]) {
printerr_line(k);
exit(1);
}
}
}
if (str[mx_strlen(str) - 1] == '\n') {
printerr_line(k);
exit(1);
}
}
static void INVLD_FILE(int c, char *v[]) {
if (c != 2) { // chech for arguments = 2
mx_printerr("usage: ./pathfinder [filename]\n");
exit(1);
}
int file = open(v[1], O_RDONLY);
if (file < 0) { // chech if v[1] exists
mx_printerr("error: file ");
mx_printerr(v[1]);
mx_printerr(" does not exist\n");
exit(1);
}
char buf[1]; // chech if v[1] isn't empty
int n = read(file, buf, sizeof(buf));
if (n <= 0) {
mx_printerr("error: file ");
mx_printerr(v[1]);
mx_printerr(" is empty\n");
exit(1);
}
if (buf[0] == '\n') {
printerr_line(0);
exit(1);
}
close(file);
}
static void INVLD_LINE1_DIGIT(char *strarr) {
for (int i = 1; i < mx_strlen(strarr); i++) {
if (!mx_isdigit(strarr[i])) {
mx_printerr("error: line 1 is not valid\n");
exit(1);
}
}
}
static void INVLD_LINE_INPUT(char **strarr) {
for (int i = 1; strarr[i]; i++) {
int count_space = 0;
int count_comma = 0;
int get_char = 0;
for (int j = 0; strarr[i][j] && count_space < 2; j++) {
get_char = mx_get_char_index(&strarr[i][j], '-');
if (get_char != -1) {
count_space += 1;
j += get_char;
}
else break;
}
for (int j = 0; strarr[i][j] && count_comma < 2; j++) {
get_char = mx_get_char_index(&strarr[i][j], ',');
if (get_char != -1) {
count_comma += 1;
j += get_char;
}
else break;
}
if (count_comma != 1 || count_space != 1) {
printerr_line(i);
exit(1);
}
}
}
static void INVLD_LINE_ASCII(char **strarr) {
char **tmp = NULL;
for (int i = 1; strarr[i]; i++) {
tmp = mx_pf_split(strarr[i]);
if (tmp[0][0] == '\0' || tmp[1][0] == '\0' || tmp[2][0] == '\0')
printerr_line(i);
for (int j = 0; j < mx_strlen(tmp[0]); j++) {
if (!mx_isalpha(tmp[0][j])) {
printerr_line(i);
}
}
for (int j = 0; j < mx_strlen(tmp[1]); j++) {
if (!mx_isalpha(tmp[1][j])) {
printerr_line(i);
}
}
for (int j = 0; j < mx_strlen(tmp[2]); j++) {
if (!mx_isdigit(tmp[2][j])) {
printerr_line(i);
}
}
mx_del_strarr(&tmp);
}
}
static void printerr_line(int i) {
mx_printerr("error: line ");
mx_printerr(mx_itoa(i + 1));
mx_printerr(" is not valid\n");
exit(1);
}
<file_sep>#include "libmx.h"
char *mx_strstr(const char *haystack, const char *needle) {
char *s = (char *) haystack;
if (!*needle) return s;
int ln = mx_strlen(needle);
while (*s) {
for (int i = 0; i < ln && s[i] == needle[i]; i++) {
if (needle[i + 1] == '\0') {
return s;
}
}
s++;
}
return NULL;
}
<file_sep>#include "libmx.h"
int mx_memcmp(const void *s1, const void *s2, size_t n) {
const char *d = s1;
const char *s = s2;
size_t i = 0;
while (i < n) {
if (d[i] != s[i]) {
return d[i] - s[i];
}
i++;
}
return 0;
}
<file_sep>#include "libmx.h"
int **mx_create_matrix(int G, int fillin)
{
int **str = (int **) malloc(G * sizeof(int *));
for (int i = 0; i < G; i++) {
int *s = malloc(G * sizeof(int));
for (int j = 0; j < G; j++) {
s[j] = fillin;
}
str[i] = s;
}
return str;
}
<file_sep>#include "libmx.h"
void mx_del_matrix_int(int **str) {
if (*str && str) {
free(*str);
*str = NULL;
}
}
// void mx_del_matrix_int(int **str) {
// int i = 0;
// if (str[i] != NULL) {
// free(str[i]);
// str[i] = NULL;
// }
// free(str);
// str = NULL;
// }
// void mx_del_matrix_int(int **str) {
// for (int i = 0; str[i] && malloc_size(str[i]); i++) {
// free(str[i]);
// str = NULL;
// }
// }
// void mx_del_matrix_int(int **str) {
// int **p = str;
// while (*p) {
// free(*p);
// *p = NULL;
// (*p)++;
// }
// free(p);
// str = NULL;
// }
<file_sep>#include "libmx.h"
char *mx_file_to_str(const char *file) {
if (!file) return NULL;
int k = 0;
char buf[1];
// count bytes
int f = open(file, O_RDONLY);
if (f < 0) return NULL;
int n = read(f, buf, sizeof(buf));
if (n <= 0) return NULL;
while (n > 0) {
k++;
n = read(f, buf, sizeof(buf));
}
close(f);
// copy to string
f = open(file, O_RDONLY);
char *s = mx_strnew(k);
char *p = s;
int m = read(f, buf, sizeof(buf));
while (m > 0) {
*s = *buf;
m = read(f, buf, sizeof(buf));
s++;
}
close(f);
return p;
}
<file_sep>#include "libmx.h"
int mx_count_words_isspace(const char *str, int *kwl) {
if (!str || !*str) return -1;
int s = 0;
int i = 0;
while (str[i] != '\0') {
// if not word
if (mx_isspace(str[i]))
while (mx_isspace(str[i]) && str[i] != '\0')
i++;
// if word
if (!mx_isspace(str[i]) && str[i] != '\0') {
s++;
while (!mx_isspace(str[i]) && str[i] != '\0') {
i++;
*kwl += 1;
}
}
}
return s;
}
<file_sep>#include "libmx.h"
int **mx_create_dex_matrix(int **matrix, int g)
{
int INFINITY = 999999;
int **dex = mx_create_matrix(g, INFINITY);
for (int i = 0; i < g; i++)
for (int j = 0; j < g; j++)
if (matrix[i][j] != 0)
dex[i][j] = matrix[i][j];
return dex;
}
<file_sep>#include "libmx.h"
static void print_border();
static void print_path(t_all_paths *paths, char **arr_islands);
static void print_route(t_all_paths *paths, char **arr_islands);
static void print_distance(t_all_paths *paths, int **matrix);
void mx_printpaths(t_all_paths *paths, int **matrix, char **arr_islands)
{ //print the path and distance of each node
t_all_paths *q = paths;
if (paths != NULL) {
for (; q != NULL; q = q->next) {
print_border();
print_path(q, arr_islands);
print_route(q, arr_islands);
print_distance(q, matrix);
print_border();
}
}
else {
mx_printstr("paths == 0 (NULL)\n");
}
}
static void print_border()
{
for (int k = 0; k < 40; k++)
mx_printchar('=');
mx_printstr("\n");
}
static void print_path(t_all_paths *paths, char **arr_islands)
{
mx_printstr("Path: ");
mx_printstr(arr_islands[paths->path[0]]);
mx_printstr(" -> ");
mx_printstr(arr_islands[paths->path[paths->count - 1]]);
mx_printstr("\n");
}
static void print_route(t_all_paths *paths, char **arr_islands)
{
mx_printstr("Route: ");
for (int i = 0; i < paths->count; i++) {
mx_printstr(arr_islands[paths->path[i]]);
if (i == paths->count - 1) break;
mx_printstr(" -> ");
}
mx_printstr("\n");
}
static void print_distance(t_all_paths *paths, int **matrix)
{
int j = 1;
mx_printstr("Distance: ");
if (paths->count > 2) {
while (j < paths->count) {
mx_printint(matrix[paths->path[j - 1]][paths->path[j]]);
if (j == paths->count - 1) break;
mx_printstr(" + ");
j++;
}
mx_printstr(" = ");
}
mx_printint(paths->distance);
mx_printstr("\n");
}
<file_sep>#include "libmx.h"
void mx_del_arr_matrix_int(int ***arr) {
if (arr == NULL) return;
int ***p = arr;
int **pp = *arr;
while (**p != NULL) {
mx_del_matrix_int(*p);
(*p)++;
}
free(pp);
*arr = NULL;
}
<file_sep>#include "libmx.h"
static int **initialize_pred(int g, int startnode);
static void initialize_visited(int *visited, int g, int startnode);
static void initialize_distance(int *distance, int g, int startnode, int **dex);
int **mx_alg_deijkstra(int **dex, int *distance, int g, int startnode)
{
int INFINITY = 999999;
int visited[g], count, mindistance, nextnode, i;
int **pred = initialize_pred(g, startnode);
initialize_visited(visited, g, startnode);
initialize_distance(distance, g, startnode, dex);
count = 1;
while (count < g - 1) {
mindistance = INFINITY;
//nextnode gives the node at minimum distance
for (i = 0; i < g; i++)
if (distance[i] < mindistance && !visited[i]) {
mindistance = distance[i];
nextnode = i;
}
//check if a better path exists through nextnode
visited[nextnode] = 1;
for (i = 0; i < g; i++)
if (!visited[i]) {
if (mindistance + dex[nextnode][i] < distance[i]) {
distance[i] = mindistance + dex[nextnode][i];
pred[0][i] = nextnode;
pred[1][i] = nextnode;
}
if (mindistance + dex[nextnode][i] == distance[i]) {
pred[1][i] = nextnode;
}
}
count++;
}
return pred;
}
static int **initialize_pred(int g, int startnode)
{
int **pred = malloc (3 * sizeof(int *));
pred[0] = malloc(g * sizeof(int));
pred[1] = malloc(g * sizeof(int));
pred[2] = NULL;
for (int i = 0; i < g; i++) {
pred[0][i] = startnode;
pred[1][i] = startnode;
}
return pred;
}
static void initialize_visited(int *visited, int g, int startnode)
{
for (int i = 0; i < g; i++) {
visited[i] = 0;
}
visited[startnode] = 1;
}
static void initialize_distance(int *distance, int g, int startnode, int **dex)
{
for (int i = 0; i < g; i++) {
distance[i] = dex[startnode][i];
}
distance[startnode] = 0;
}
<file_sep># pathfinder
### description:
```
Ucode project: develop an algorithm that finds the shortest paths between the points.
---
Designed using the Dijksta algorithm, works on simple graphs.
Finds the shortest path, and if there are another shortest paths of the same length, find only one more as well.
Gets input data from file.
```
### usage:
```
1. git clone
2. make
3. ./pathfinder [filename]
```
**input example:**
```
4
Greenland-Bananal,8
Fraser-Greenland,10
Bananal-Fraser,3
Java-Fraser,5
```
**output example:**
```
./pathfinder path | cat -e
========================================$
Path: Greenland -> Bananal$
Route: Greenland -> Bananal$
Distance: 8$
========================================$
========================================$
Path: Greenland -> Fraser$
Route: Greenland -> Fraser$
Distance: 10$
========================================$
========================================$
Path: Greenland -> Java$
Route: Greenland -> Fraser -> Java$
Distance: 10 + 5 = 15$
========================================$
========================================$
Path: Bananal -> Fraser$
Route: Bananal -> Fraser$
Distance: 3$
========================================$
========================================$
Path: Bananal -> Java$
Route: Bananal -> Fraser -> Java$
Distance: 3 + 5 = 8$
========================================$
========================================$
Path: Fraser -> Java$
Route: Fraser -> Java$
Distance: 5$
========================================$
```
<file_sep>#include "libmx.h"
char **mx_pf_split(const char *s) {
if (!s) return NULL;
char **res = (char **) malloc((3 + 1) * sizeof(char *));
int n = mx_get_char_index(s, '-');
res[0] = mx_strndup(s, n);
s += mx_strlen(res[0]) + 1;
n = mx_get_char_index(s, ',');
res[1] = mx_strndup(s, n);
s += mx_strlen(res[1]) + 1;
res[2] = mx_strdup(s);
res[3] = NULL;
return res;
}
<file_sep>#include "libmx.h"
int main(int c, char *v[])
{
mx_pf_errors(c, v); // find all errors
char *str = mx_file_to_str(v[1]);
char **strarr = mx_strsplit(str, '\n');
int G = mx_atoi(str); // count of islands
// create line of names & check for line1
char **arr_islands = mx_get_arr_islands(G, strarr);
int **matrix = mx_get_matrix(G, str, arr_islands); // create adj matrix
int **dex = mx_create_dex_matrix(matrix, G); // create dex matrix
t_all_paths *paths = mx_get_all_paths(dex, G); // get linled list of paths
mx_printpaths(paths, matrix, arr_islands); // print paths
mx_strdel(&str); // clean all created
mx_del_strarr(&strarr);
mx_strdel(arr_islands);
mx_del_matrix_int(matrix);
mx_del_matrix_int(dex);
return 0;
}
<file_sep>#include "libmx.h"
int mx_get_substr_index(const char *str, const char *sub) {
if (!str || !sub || !*str || !*sub) return -2;
char *s = (char *)str;
int j = 0;
while (*s) {
int i = 0;
for (i = 0; i < mx_strlen(sub) && s[i] == sub[i]; i++) {
if (sub[i + 1] == '\0') {
return j;
}
}
s++;
j++;
}
return -1;
}
<file_sep>NAME = pathfinder
CFLAGS = -std=c11 -Wall -Wextra -Werror -Wpedantic
# --------- Header files ----------------
INC = libmx.h
INCI = $(addprefix inc/, \
libmx.h)
# --------- Source files ----------------
SRC = pf_main.c mx_create_dex_matrix.c mx_deijkstra.c mx_get_all_paths.c mx_get_arr_islands.c mx_get_matrix.c mx_pf_errors.c mx_pf_split.c mx_printpaths.c
SRCS = $(addprefix src/, \
pf_main.c mx_create_dex_matrix.c mx_deijkstra.c mx_get_all_paths.c mx_get_arr_islands.c mx_get_matrix.c mx_pf_errors.c mx_pf_split.c mx_printpaths.c)
# --------- Object files ----------------
OBJ = pf_main.o mx_create_dex_matrix.o mx_deijkstra.o mx_get_all_paths.o mx_get_arr_islands.o mx_get_matrix.o mx_pf_errors.o mx_pf_split.o mx_printpaths.o
# ---------------------------------------
all: install uninstall
install:
@ make install -sC libmx/
@ cp $(SRCS) $(INCI) .
@ clang $(CFLAGS) -c $(SRC)
@ clang $(CFLAGS) $(OBJ) libmx/libmx.a -o $(NAME)
@ mkdir ./obj
@ mv $(OBJ) ./obj
uninstall:
@ make uninstall -sC libmx/
@ rm -rf $(INC) $(SRC) ./obj
clean: uninstall
@ make clean -sC libmx/
@ rm -rf $(NAME)
reinstall: clean all
<file_sep>#include "libmx.h"
void mx_printarrint(int *arr, int G)
{
if (!arr) return;
for (int i = 0; i < G; i++){
mx_printint(arr[i]);
mx_printstr(" ");
}
mx_printstr("\n");
}
<file_sep>#include "libmx.h"
int **mx_get_matrix(int G, char *str, char **arr_islands)
{
int **matrix = mx_create_matrix(G, 0); //--------------- c-2
char **strarr = mx_strsplit(str, '\n'); //--------------- c-3
for (int i = 0; strarr[i]; i++) {
int mi = 0;
int mj = 0;
char **tmp = mx_pf_split(strarr[i]); //--------------- c-4
for (int j = 0; j < G; j++) {
if (mx_strcmp(arr_islands[j], tmp[0]) == 0) {
mi = j;
}
if (mx_strcmp(arr_islands[j], tmp[1]) == 0) {
mj = j;
}
}
matrix[mi][mj] = mx_atoi(tmp[2]);
matrix[mj][mi] = mx_atoi(tmp[2]);
mx_del_strarr(&tmp); //--------------- d-4
}
mx_del_strarr(&strarr);//--------------- d-3
return matrix;//--------------- r-2
}
<file_sep>#include "libmx.h"
bool mx_cmp(void *a, void *b) {
if (*(char *)a > *(char *)b)
return true;
else return false;
}
<file_sep>#include "libmx.h"
static int *get_route(int i, int *pred, int startnode, int *count);
static t_all_paths *mx_create_path(int c, int *route, int *d);
static void mx_push_back_path(t_all_paths **paths, int c, int *route, int *d);
static bool compare_arr_int(int count1, int count2, int *arr1, int *arr2);
t_all_paths *mx_get_all_paths(int **dex, int G)
{
t_all_paths *paths = NULL;
for (int startnode = 0; startnode < G - 1; startnode++) {
int *distance = malloc (G * sizeof(int));
int **pred = mx_alg_deijkstra(dex, distance, G, startnode);
bool flag = compare_arr_int(G, G, pred[0], pred[1]);
// поиск всех путей от начальной точки до заданной
for (int i = startnode + 1; i < G; i++) {
//if (i != startnode) {
int count0 = 0;
int *route0 = get_route(i, pred[0], startnode, &count0);
if (!flag) {
int count1 = 0;
int *route1 = get_route(i, pred[1], startnode, &count1);
if (!compare_arr_int(count0, count1, route0, route1))
mx_push_back_path(&paths, count1, route1, &distance[i]);
else free(route1);
}
mx_push_back_path(&paths, count0, route0, &distance[i]);
//}
}
mx_del_arr_matrix_int(&pred);
free(distance);
}
return paths;
}
static int *get_route(int i, int *pred, int startnode, int *count)
{
int j = i;
int k = 0;
while (j != startnode) {
j = pred[j];
k++;
}
j = i;
*count = k + 1;
int *route = malloc((k + 1) * sizeof(int));
route[k] = i;
while (j != startnode && k > 0) {
j = pred[j];
k--;
route[k] = j;
}
return route;
}
static t_all_paths *mx_create_path(int c, int *route, int *d)
{
t_all_paths *temp;
if (!c || !route || !d) return NULL;
temp = malloc(sizeof(t_all_paths));
if (!temp) return NULL;
temp->number = 0;
temp->count = c;
temp->path = route;
temp->distance = *d;
temp->next = NULL;
return temp;
}
static void mx_push_back_path(t_all_paths **paths, int c, int *route, int *d)
{
t_all_paths *tmp;
t_all_paths *p;
if (!paths || !c || !route || !d) return;
tmp = mx_create_path(c, route, d); // create new
if (!tmp) return;
p = *paths;
if (*paths == NULL) { // find Null-node
*paths = tmp;
return;
}
else {
while (p->next != NULL) // find Null-node
p = p->next;
p->next = tmp;
}
}
static bool compare_arr_int(int count1, int count2, int *arr1, int *arr2)
{
if (!arr1 || !arr2) return false;
if (count1 == count2) {
for (int i = 0; arr1[i] == arr2[i]; i++) {
if (i == count1 - 1) {
return true;
}
}
}
return false;
}
<file_sep>#include "libmx.h"
char **mx_strsplit(const char *s, char c) {
if (!s) return NULL;
int size = mx_count_words(s, c);
char **res = (char **) malloc((size + 1) * sizeof (char *));
int i_res = 0;
int i_del = 0;
if (size == 1) {
res[0] = mx_strdup(s);
res[1] = NULL;
return res;
}
while (*s) {
i_del = mx_get_char_index(s, c);
i_del = i_del == -1 ? i_del = mx_strlen(s) : i_del;
if (i_del) {
res[i_res] = mx_strndup(s, i_del);
s += mx_strlen(res[i_res]) - 1;
i_res++;
}
s++;
}
res[i_res] = NULL;
return res;
}
<file_sep>#include "libmx.h"
void *mx_memchr(const void *s, int c, size_t n) {
const char *d = s;
size_t i = 0;
while (i < n) {
if (d[i] == c) {
return (void *)&d[i];
}
i++;
}
return NULL;
}
|
fcdbcd82deee9200d9f6b204988c1e369c0ff0b4
|
[
"Makefile",
"Markdown",
"C"
] | 27 |
Makefile
|
trohalska/pathfinder
|
738410903e563b5cc41d1a0c670a30bb87e5af97
|
40ef09760cff531771416e63fa35c955cc6da3e2
|
refs/heads/master
|
<repo_name>vf-sohail/Lexi<file_sep>/LexiEditor/src/GUIFactory/GUIFactory.java
package GUIFactory;
import GUIComponents.Menu.*;
import GUIComponents.Button.*;
import GUIComponents.ScrollBar.*;
public abstract class GUIFactory {
public abstract Menu CreateMenu();
public abstract Button CreateButton();
public abstract ScrollBar CreateScrollBar();
}
<file_sep>/LexiEditor/src/GUIComponents/Menu/Menu.java
package GUIComponents.Menu;
public abstract class Menu {
public abstract String render();
}
<file_sep>/LexiEditor/src/GUIComponents/ScrollBar/ScrollBar.java
package GUIComponents.ScrollBar;
public abstract class ScrollBar {
public abstract String render();
}
<file_sep>/LexiEditor/src/GUIComponents/ScrollBar/PMScroll.java
package GUIComponents.ScrollBar;
public class PMScroll extends ScrollBar {
public String render()
{
return "This is PMScroll";
}
}
<file_sep>/LexiEditor/src/GUIComponents/ScrollBar/MotiScroll.java
package GUIComponents.ScrollBar;
public class MotiScroll extends ScrollBar {
public String render()
{
return "This is moti Scroll";
}
}
<file_sep>/LexiEditor/src/CompositePattern/Rectangle.java
package CompositePattern;
import Models.Coordinates;
import java.awt.Graphics;
public class Rectangle extends Glyph {
int width ;
int height;
public Rectangle(Coordinates coordinates, int width,int height )
{
this._coordinates=coordinates;
this.width=width;
this.height=height;
}
@Override
public void Draw(Graphics window) {
int x=_coordinates.x;
int y=_coordinates.y;
window.drawRect(x,y,width,height);
}
@Override
public Coordinates Bound() throws Exception {
//returns the space that the gylph occupies
return _coordinates;
}
@Override
public boolean Intersects(Coordinates coordinates) throws Exception {
if(coordinates.x==_coordinates.x && coordinates.y==_coordinates.y )
{
return true;
}
else
{
return false;
}
}
}
<file_sep>/LexiEditor/src/GUIComponents/Menu/MacMenu.java
package GUIComponents.Menu;
public class MacMenu extends Menu{
public String render()
{
return "This is MacMenu";
}
}
<file_sep>/LexiEditor/src/GUIComponents/Button/MacButton.java
package GUIComponents.Button;
public class MacButton extends Button {
public String render()
{
return "This is MacButton";
}
}
|
723a17ecf6b04dde9623a0f4d9b55b7471bb26d7
|
[
"Java"
] | 8 |
Java
|
vf-sohail/Lexi
|
938e98023202a33fe8697f96e023b960715ab1aa
|
8064befe04bd8c3d4c4f399ba0376c9e02a440cb
|
refs/heads/master
|
<repo_name>carolinapc/skillshub<file_sep>/client/src/pages/Profile/Skills.jsx
import React from 'react';
import API from '../../utils/API';
import SkillsList from './SkillsList';
import SkillForm from './SkillForm';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
class Skills extends React.Component {
mounted = false;
state = {
userSkills: [],
categories: [],
editionView: false,
fields: {
id: "",
name: "",
description: "",
price: "",
priceType: "",
zipCode: "",
active: false,
CategoryId: ""
},
controllers: {
message: "",
error: false,
isLoading: false
}
}
//guarantees the setState won't be called after component unmounts
componentWillUnmount = () => this.mounted = false;
componentDidMount = () => {
this.mounted = true;
this.refreshUserSkills();
//get all categories
API.getCategories().then(res => {
if (res.data) {
if (this.mounted) {
this.setState({categories: res.data});
}
}
else {
console.log("There are no categories stored!");
}
}).catch(err => console.log(err.response));
}
refreshUserSkills = () => {
//fill all the fields from database
API.getUserSkills().then(res => {
if (res.data) {
if (this.mounted) {
this.setState({ userSkills: res.data });
}
}
else {
console.log("User doesn't have skills registered!");
}
}).catch(err => console.log(err.response));
}
handleInputChange = event => {
let { name, value } = event.target;
let fields = { ...this.state.fields };
//if it's a checkbox gets the checked value
if (event.target.type === "checkbox") {
value = event.target.checked;
}
fields[name] = value;
this.setState({ fields: fields });
}
editSkill = skill => {
this.setState({
editionView: true,
fields: skill,
controllers: {
error: false,
message: "",
isLoading: false
}
});
}
viewSkillsList = () => this.setState({ editionView: false });
addSkill = () => {
let skill = {
id: "",
name: "",
description: "",
price: "",
priceType: "",
zipCode: "",
active: false,
CategoryId: ""
};
this.editSkill(skill);
}
toogleActive = event => {
const { id, checked } = event.target;
API.updateUserSkill({ active: checked, id }).then(res => {
let userSkills = [...this.state.userSkills];
userSkills.map(skill => {
if (skill.id.toString() === id) {
skill.active = checked;
}
return skill;
});
if (this.mounted) {
this.setState({userSkills});
}
}).catch(err => console.log(err.response));
}
saveSkill = () => {
let controllers = { ...this.state.controlers };
controllers.error = false;
controllers.isLoading = true;
if (this.state.fields.id !== "") {
API.updateUserSkill(this.state.fields)
.then(res => {
controllers.message = "Skill updated successfully";
controllers.isLoading = false;
if (this.mounted) {
this.setState({ controllers });
}
this.refreshUserSkills();
this.viewSkillsList();
toast.info("Skill was updated successfully",{position: toast.POSITION.BOTTOM_RIGHT});
})
.catch(err => {
if (err.response.data.errors) {
controllers.message = err.response.data.errors[0].message;
}
else {
controllers.message = err.response.data;
}
controllers.isLoading = false;
controllers.error = true;
if (this.mounted) {
this.setState({ controllers: controllers });
}
});
}
else {
API.createUserSkill(this.state.fields)
.then(res => {
controllers.message = "Skill was created successfully";
controllers.isLoading = false;
if (this.mounted) {
this.setState({ controllers });
}
this.refreshUserSkills();
this.viewSkillsList();
toast.info("Skill was created successfully!",{position: toast.POSITION.BOTTOM_RIGHT});
})
.catch(err => {
if (err.response.data.errors) {
controllers.message = err.response.data.errors[0].message;
}
else {
controllers.message = err.response.data;
}
controllers.isLoading = false;
controllers.error = true;
if (this.mounted) {
this.setState({ controllers });
}
});
}
}
render() {
return (
<>
<ToastContainer />
{this.state.editionView ?
<SkillForm
skill={this.state.fields}
handleInputChange={this.handleInputChange}
controllers={this.state.controllers}
categories={this.state.categories}
saveSkill={this.saveSkill}
viewSkillsList={this.viewSkillsList}
/>
:
<SkillsList
addSkill={this.addSkill}
editSkill={this.editSkill}
userSkills={this.state.userSkills}
toogleActive={this.toogleActive}
/>
}
</>
);
}
}
export default Skills;<file_sep>/routes/api/category.js
const router = require("express").Router();
const categoryController = require("../../controllers/categoryController");
// Matches with "/api/category"
router.route("/")
.get(categoryController.findAll);
// Matches with "/api/category/grouped"
router.route("/grouped")
.get(categoryController.findAllGrouped);
module.exports = router;<file_sep>/client/src/pages/Search/SkillsSearchList.jsx
import React from 'react';
import './style.css';
import Utils from '../../utils';
import { NavLink } from 'react-router-dom';
import {Button} from 'react-bootstrap';
const SkillsSearchList = props => {
const getMapLink = ({ latitude, longitude }) => {
if (props.zipCode) {
return `https://www.google.com.br/maps/dir/${props.zipCode}/${latitude},${longitude}`;
}
else {
return `http://www.google.com.br/maps/place/${latitude},${longitude}`;
}
}
return (
<>
{props.skills.map(skill => {
return (
<div className="card shadow-sm bg-light mt-3" key={skill.id}>
<div className="card-body">
<h4 className="card-title">{skill.User.firstName}</h4>
<div className="wrap-price">
<h4>{Utils.getStars(skill.score)}</h4>
<h4>${skill.price + " per " + Utils.getPriceTypeName(skill.priceType)}</h4>
<h5>
{skill.distance ? `${skill.distance} km` : null}
<Button variant="outline-secondary" className="ml-3 btn-sm" href={getMapLink(skill)} target="_blank">
<i className="far fa-map"></i> View Map
</Button>
</h5>
</div>
<div className="card-text description">
<img src={skill.User.image ? `/${skill.User.image}` : "/profile.jpg"} alt="Profile" className="shadow-lg" onError={() => props.handleSkillImgError(skill.id)} />
<div>
<h3 className="card-subtitle mb-2 text-muted">{skill.name}</h3>
<h5 className="card-subtitle mb-2 text-muted">{skill.Category.name}</h5>
<p>{Utils.replaceNewLines(skill.description)}</p>
<NavLink
exact
to={`/skill/${skill.id}?dist=${skill.distance}&zip=${props.zipCode}`}
activeClassName="active"
className="btn btn-secondary"
>
View
</NavLink>
</div>
</div>
</div>
</div>
);
})}
</>
);
}
export default SkillsSearchList;<file_sep>/client/src/pages/Profile/ChangePassword.jsx
import React from 'react';
import { Form, Button } from 'react-bootstrap';
import API from '../../utils/API';
class ChangePassword extends React.Component {
state = {
password: "",
newPassword: "",
confirmPassword: "",
message: "",
error: false,
isLoading: false
}
handleInputChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value, message: "" });
}
updateInfo = () => {
const { password, confirmPassword, newPassword } = this.state;
if (newPassword !== confirmPassword) {
this.setState({ message: "Passwords must match", error: true, isLoading: false });
}
else {
API.changePassword({ password, newPassword })
.then(() => {
this.setState({ message: "Password updated successfully", error: false, isLoading: false });
})
.catch(err => {
let message;
if (err.response.data.errors) {
message = err.response.data.errors[0].message;
}
else {
message = err.response.data;
}
this.setState({ message, error: true, isLoading: false });
});
}
}
render() {
return (
<Form>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" name="password" value={this.state.password} placeholder="<PASSWORD>" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicNewPassword">
<Form.Label>New Password</Form.Label>
<Form.Control type="password" name="newPassword" value={this.state.newPassword} placeholder="New password" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicConfirmPassword">
<Form.Label>Confirm Password</Form.Label>
<Form.Control type="password" name="confirmPassword" value={this.state.confirmPassword} placeholder="Confirm new password" onChange={this.handleInputChange} />
</Form.Group>
<div className={this.state.error?"text-danger":"text-success"}>{this.state.message}</div>
<Button
variant="secondary"
disabled={this.state.isLoading}
onClick={!this.state.isLoading ? this.updateInfo : null}
className="mt-3"
>
<i className="fas fa-check"></i> Save
</Button>
</Form>
);
}
}
export default ChangePassword;<file_sep>/client/src/components/Footer/index.jsx
import React from 'react';
import './style.css';
const Footer = () => {
return (
<footer className="bg-dark text-white p-2 mt-auto text-center">
© Skillshub <br/>
</footer>
);
}
export default Footer;<file_sep>/routes/api/user.js
const router = require("express").Router();
const userController = require("../../controllers/userController");
// Matches with "/api/user"
router.route("/")
.get(userController.findAll)
.put(userController.update)
.post(userController.create);
// Matches with "/api/user/find/:id"
router.route("/find/:id")
.get(userController.findById);
// Matches with "/api/user/account"
router.route("/account")
.get(userController.getUserAccount);
// Matches with "/api/user/skills"
router.route("/skills")
.get(userController.getUserSkills)
.post(userController.createUserSkill)
.put(userController.updateUserSkill);
// Matches with "/api/user/resetpwd"
router.route("/resetpwd").post(userController.resetPassword);
// Matches with "/api/user/changepwd"
router.route("/changepwd").post(userController.changePassword);
// Matches with "/api/user/auth"
router.route("/auth").get(userController.getUserSession);
router.route("/auth").post(userController.auth);
// Matches with "/api/user/signout"
router.route("/signout")
.post(userController.signout);
module.exports = router;
<file_sep>/client/src/components/WithAuth/index.jsx
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import API from '../../utils/API';
export default function WithAuth(ComponentToProtect) {
return class extends Component {
mounted = false;
constructor() {
super();
this.state = {
loading: true,
redirect: false,
userData: {}
};
}
componentDidMount = () => {
this.mounted = true;
//check authentication status
API.getUserSession().then(res => {
if (this.mounted) {
if (res.data.loggedin) {
this.setState({ loading: false, userData: res.data });
}
else {
this.setState({ loading: false, redirect: true });
}
}
}).catch(err => console.log(err));
}
componentWillUnmount = () => {
this.mounted = false;
}
render() {
const { loading, redirect } = this.state;
if (loading) {
return null;
}
if (redirect) {
return <Redirect to="/" />;
}
return (
<React.Fragment>
<ComponentToProtect userData={this.state.userData} {...this.props} />
</React.Fragment>
);
}
}
}<file_sep>/client/src/pages/Search/index.jsx
import React from 'react';
import API from '../../utils/API';
import {Form, Button, Row, Col} from 'react-bootstrap';
import PageContainer from '../../components/PageContainer';
import SkillsSearchList from './SkillsSearchList';
class Search extends React.Component {
mounted = false;
constructor(props) {
super(props);
let params = new URLSearchParams(this.props.location.search);
this.state = {
categoryId: params.get('category') || "",
search: params.get('search') || "",
zipCode: params.get('postal') || "",
latitude: params.get('lat') || "",
longitude: params.get('lng') || "",
distanceRange: "5",
skills: [],
categories: [],
notFoundMsg: ""
}
}
componentDidMount = () => {
this.mounted = true;
this.searchSkills();
//get all categories to fill dropdown list
API.getCategories().then(res => {
if (res.data) {
if (this.mounted) {
this.setState({categories: res.data});
}
}
else {
console.log("There are no categories stored!");
}
}).catch(err => console.log(err.response));
}
componentWillUnmount() {
this.mounted = false;
}
searchSkills = () => {
let data = {
search: this.state.search || "",
categoryId: this.state.categoryId || "",
zipCode: this.state.zipCode || "",
distanceRange: this.state.distanceRange || "",
latitude: this.state.latitude || "",
longitude: this.state.longitude || ""
}
//get all skills filtering by data passed
API.getSkills(data)
.then(res => {
if (this.mounted) {
if (res.data.length > 0) {
this.setState({ skills: res.data, notFoundMsg: "" });
}
else {
this.setState({ skills:[],notFoundMsg: "Sorry... skills not found" });
}
}
})
.catch(err => {
this.setState({ skills: [], notFoundMsg: "Oops.. something is wrong. Please try again." });
});
}
handleSearch = event => {
event.preventDefault();
this.searchSkills();
}
handleInputChange = event => {
const { name, value } = event.target;
//if a new postal code is informed then it cleans the geo location
if (name === "zipCode") {
this.setState({ [name]: value, latitude: "", longitude: "" });
}
else {
this.setState({ [name]: value });
}
}
handleSkillImgError = skillId => {
let skills = this.state.skills;
skills.map(skill => {
if (skill.id === skillId) {
skill.User.image = "profile.jpg";
}
return skill;
});
this.setState({ skills });
}
render() {
return (
<PageContainer title="Search Skills">
<Row>
<Col md="6">
<Form.Group controlId="formBasicName">
<Form.Label>Search</Form.Label>
<Form.Control type="text" name="search" value={this.state.search||""} placeholder="Enter a skill to search" onChange={this.handleInputChange} />
</Form.Group>
</Col>
<Col md="6">
<Form.Group controlId="formBasicPostal">
<Form.Label>Postal Code</Form.Label>
<Form.Control type="text" name="zipCode" value={this.state.zipCode || ""} placeholder="Postal Code" onChange={this.handleInputChange} />
</Form.Group>
</Col>
</Row>
<Row>
<Col>
<Form.Label>Category</Form.Label>
<Form.Control as="select" name="categoryId" onChange={this.handleInputChange} value={this.state.categoryId||""}>
<option key="blankCategory" value="">-- All Categories --</option>
{this.state.categories.map(category => {
return (
<option key={category.id} value={category.id}>{category.name}</option>
);
})}
</Form.Control>
</Col>
<Col>
<div className="form-group">
<label htmlFor="formControlRange">Distance Range: {this.state.distanceRange} km</label>
<input type="range" name="distanceRange" className="custom-range" min="5" max="100" step="1" id="formControlRange" value={this.state.distanceRange} onChange={this.handleInputChange} />
</div>
</Col>
</Row>
<Row className="mb-4 mt-0">
<Col md="12">
<Button variant="secondary" onClick={this.handleSearch} className="mt-3">Search</Button>
</Col>
</Row>
<Row>
<Col md="12">
{this.state.skills.length > 0 ?
<SkillsSearchList skills={this.state.skills} handleSkillImgError={this.handleSkillImgError} zipCode={this.state.zipCode} />
: <div className="message">{this.state.notFoundMsg}</div>
}
</Col>
</Row>
</PageContainer>
);
}
}
export default Search;<file_sep>/controllers/contactController.js
const db = require("../models");
const Moment = require("moment");
// Defining methods for the Contacts
module.exports = {
/*
Gets all requests made by the user
*/
findUserRequests: function (req, res) {
//checks if the user is logged in
if (!req.session.loggedin) {
res.status(400).end("You need to sign in to see contacts.");
}
else {
db.Contact.findAll({
include: [{ all: true, nested: true }],
where: {
UserId: req.session.UserId,
active: true,
dealCLosed: false
}
})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
},
/*
Get all clients from user
*/
findUserClients: function (req, res) {
//checks if the user is logged in
if (!req.session.loggedin) {
res.status(400).end("You need to sign in to see contacts.");
}
else {
db.Contact.findAll({
include: [{ all: true, nested: true }],
where: {
[db.Sequelize.Op.and]: db.Sequelize.literal(`Skill.UserId = ${req.session.UserId}`),
active: true,
dealCLosed: false
}
})
.then(dbModel => res.json(dbModel))
.catch(err => { console.log(err); res.status(422).json(err) });
}
},
/*
Get a contact made by the client related to a skill passed that is still opened
*/
findOneBySkill: function (req, res) {
//checks if the user is logged in
if (!req.session.loggedin) {
res.status(400).end("You need to sign in to see contacts.");
}
else {
let where = { active: true };
let include = [{ all: true, nested: true }];
where.UserId = req.session.UserId;
where.dealClosed = false;
if (req.params.id) {
where.SkillId = req.params.id;
}
else {
res.status(422).json("You need to select a skill to contact the user");
}
db.Contact
.findOne({
include: include,
where: where,
order: [['createdAt', 'DESC']]
})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
},
create: function (req, res) {
//checks if the user is logged in
if (!req.session.loggedin) {
res.status(400).end("You need to sign in to see contacts.");
}
else if (req.body.text === "") {
res.status(400).end("A text must be informed.");
}
else {
req.body.UserId = req.session.UserId;
let chat = [];
chat.push({
text: req.body.text,
user: `${req.session.UserName} ${req.session.UserLastName}`,
dateTime: Moment().format('YYYYMMDDHHMMSS')
});
req.body.chat = [];
req.body.chat = JSON.stringify(chat);
delete req.body.text;
db.Contact.create(req.body)
.then(data => res.json(data))
.catch(err => res.status(422).json(err));
}
},
/*
Update a contact
*/
update: function (req, res) {
const contactId = req.body.id;
delete req.body.id;
//checks if the user is logged in
if (!req.session.loggedin) {
res.status(400).end("You need to sign in to update a contact.");
}
else {
db.Contact
.update(req.body, {where: {id: contactId} })
.then(data => res.json(data))
.catch(err => res.status(422).json(err));
}
}
}<file_sep>/client/src/pages/Profile/SkillForm.jsx
import React from 'react';
import Utils from '../../utils';
import {Form, Button, ButtonToolbar} from 'react-bootstrap';
const SkillForm = props => {
return (
<Form>
<Form.Group controlId="formBasicName">
<Form.Label>Title</Form.Label>
<Form.Control type="text" name="name" value={props.skill.name} placeholder="Enter first name" onChange={props.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicDescription">
<Form.Label>Description</Form.Label>
<Form.Control as="textarea" rows="5" name="description" value={props.skill.description} placeholder="Enter a description..." onChange={props.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicCategory">
<Form.Label>Category</Form.Label>
<Form.Control as="select" name="CategoryId" onChange={props.handleInputChange} value={props.skill.CategoryId}>
<option key="blankCategory" value="">-- select one --</option>
{props.categories.map(category => {
return (
<option key={category.id} value={category.id}>{category.name}</option>
);
})}
</Form.Control>
</Form.Group>
<Form.Group controlId="formBasicZipCode">
<Form.Label>Postal Code</Form.Label>
<Form.Control type="text" name="zipCode" value={props.skill.zipCode} placeholder="Postal Code" onChange={props.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicPrice">
<Form.Label>Price</Form.Label>
<Form.Control type="number" name="price" value={props.skill.price} placeholder="15.00" onChange={props.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicPriceType">
<Form.Label>Price Type</Form.Label>
<Form.Control as="select" name="priceType" onChange={props.handleInputChange} value={props.skill.priceType}>
<option key="blankPriceType" value="">-- select one --</option>
{Utils.getPriceTypes().map(priceType => {
return (
<option key={priceType.type} value={priceType.type}>{priceType.name}</option>
);
})}
</Form.Control>
</Form.Group>
<Form.Check
type="switch"
id="active"
name="active"
value={props.skill.active}
checked={props.skill.active}
onChange={props.handleInputChange}
label="Available"
/>
<div className={props.controllers.error ? "text-danger" : "text-success"}>{props.controllers.message}</div>
<ButtonToolbar>
<Button
variant="secondary"
disabled={props.controllers.isLoading}
onClick={!props.controllers.isLoading ? props.saveSkill : null}
className="mt-3 mr-2"
>
<i className="fas fa-check"></i> Save
</Button>
<Button
variant="secondary"
onClick={props.viewSkillsList}
className="mt-3"
>
<i className="fas fa-long-arrow-alt-left"></i> Cancel
</Button>
</ButtonToolbar>
</Form>
);
}
export default SkillForm;<file_sep>/client/src/pages/Home/CategoryList.jsx
import React from 'react';
import { Card, Row, Button } from 'react-bootstrap';
import {Link} from 'react-router-dom';
import './style.css';
const CategoryList = props => {
return (
<>
<Row className="justify-content-md-center justify-content-sm-center mt-5 mx-auto">
{props.categories.map(category => {
return (
<Link key={category.id} to={`/search/?category=${category.id}`} role="button" className="btn btn-link">
<Card style={{ width: '18rem' }} className="shadow card-custom">
<Card.Body>
<Card.Title>{category.name}</Card.Title>
<Card.Text>
<img src={"/images/categories/"+category.image} alt={category.image} />
</Card.Text>
</Card.Body>
</Card>
</Link>
);
})}
</Row>
<Row className="justify-content-md-center">
{!props.showingAllCategories ?
<Button onClick={props.pullAllCategories} variant="secondary" className="justify-content-md-center my-4 mx-auto">More Categories...</Button>
: null}
</Row>
</>
);
}
export default CategoryList;<file_sep>/models/category.js
module.exports = function (sequelize, DataTypes) {
let Category = sequelize.define("Category", {
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [3, 50],
msg: "Category name must have at least 3 and max 50 characters"
}
}
},
image: {
type: DataTypes.STRING,
allowNull: true
}
},
{
freezeTableName: true
});
return Category;
};
<file_sep>/client/src/components/AuthModal/index.jsx
import React from 'react';
import { Modal, Button, ButtonToolbar } from 'react-bootstrap';
import Form from 'react-bootstrap/Form';
import API from '../../utils/API';
import "./style.css";
class AuthModal extends React.Component {
state = {
email: "",
password: "",
confirmPassword: "",
firstName: "",
lastName: "",
message: "",
error: false,
isLoading: false,
modalSetup: {
title: "Sign In",
showFirstName: false,
showLastName: false,
showPassword: true,
showConfirmPassword: false,
showEmail: true,
showLinkSignUp: true,
showLinkReset: true,
showLinkSignIn: false,
showBtnSignUp: false,
showBtnReset: false,
showBtnSignIn: true
}
}
//authenticate user
authenticate = event => {
event.preventDefault();
this.setState({ isLoading: true });
const { email, password } = this.state;
let data = { email, password };
API.authenticate(data)
.then(res => {
this.setState({ message: "" });
this.props.handleAuthentication(res);
this.setState({ isLoading: false });
})
.catch(err => {
this.setState({ message: err.response.data, error: true });
this.setState({ isLoading: false });
});
}
//create an account
signUp = event => {
event.preventDefault();
this.setState({ isLoading: true });
const { firstName, lastName, email, password, confirmPassword } = this.state;
if (firstName.trim() === "" ||
lastName.trim() === "" ||
email.trim() === "" ||
password.trim() === "" ||
confirmPassword.trim() === "") {
this.setState({ message: "All fields are required", error: true, isLoading:false });
}
else if (password !== confirmPassword) {
this.setState({ message: "Passwords must match", error: true, isLoading:false });
}
else {
let data = {
firstName: firstName,
lastName: lastName,
email: email,
password: <PASSWORD>
};
API.signUp(data)
.then(res => {
this.setupModal("signin");
this.setState({ message: "Account was created successfully", error: false, isLoading:false });
})
.catch(err => {
let message;
if (err.response.data.errors) {
message = err.response.data.errors[0].message;
}
else {
message = err.response.data;
}
this.setState({ message, error: true, isLoading:false });
});
}
}
//send new password to user email
resetPassword = event => {
event.preventDefault();
this.setState({ isLoading: true });
let data = { email: this.state.email };
API.resetPassword(data)
.then(res => {
this.setState({ message: "Password sent to your e-mail", error:false, isLoading:false });
})
.catch(err => this.setState({ message: err.response.data, error: true, isLoading:false }));
}
handleInputChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value } );
}
//--- Begin of handling modal view state -----------------------
setupModal = viewType => {
let modalSetup = {};
if (viewType === "signup") {
modalSetup = {
title: "Sign Up",
showFirstName: true,
showLastName: true,
showPassword: true,
showConfirmPassword: true,
showEmail: true,
showLinkSignUp: false,
showLinkReset: false,
showLinkSignIn: true,
showBtnSignUp: true,
showBtnReset: false,
showBtnSignIn: false
};
}
else if (viewType === "resetpwd") {
modalSetup = {
title: "Reset Password",
showFirstName: false,
showLastName: false,
showPassword: false,
showConfirmPassword: false,
showEmail: true,
showLinkSignUp: true,
showLinkReset: false,
showLinkSignIn: true,
showBtnSignUp: false,
showBtnReset: true,
showBtnSignIn: false
};
}
else {
modalSetup = {
title: "Sign In",
showFirstName: false,
showLastName: false,
showPassword: true,
showConfirmPassword: false,
showEmail: true,
showLinkSignUp: true,
showLinkReset: true,
showLinkSignIn: false,
showBtnSignUp: false,
showBtnReset: false,
showBtnSignIn: true
};
}
this.setState({
email: "",
password: "",
confirmPassword: "",
firstName: "",
lastName: "",
message: "",
modalSetup
});
}
signUpForm = event => {
event.preventDefault();
this.setupModal("signup");
}
signInForm = event => {
event.preventDefault();
this.setupModal("signin");
}
resetPasswordForm = event => {
event.preventDefault();
this.setupModal("resetpwd");
}
onEnterModal = () => {
this.setupModal(this.props.viewType);
}
//--- End of handling modal view state -----------------------
render() {
const { title,
showEmail,
showFirstName,
showLastName,
showPassword,
showConfirmPassword,
showLinkReset,
showLinkSignIn,
showLinkSignUp,
showBtnReset,
showBtnSignIn,
showBtnSignUp
} = this.state.modalSetup;
return (
<Modal show={this.props.show} onHide={this.props.handleCloseModal} onEnter={this.onEnterModal}>
<Modal.Header closeButton>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group className={showFirstName?"":"hide-self"} controlId="formBasicFirstName">
<Form.Label>First Name</Form.Label>
<Form.Control type="text" name="firstName" value={this.state.firstName} placeholder="Enter first name" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group className={showLastName?"":"hide-self"} controlId="formBasicLastName">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" name="lastName" value={this.state.lastName} placeholder="Enter last name" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicEmail" className={showEmail?"":"hide-self"}>
<Form.Label>Email address</Form.Label>
<Form.Control type="email" name="email" value={this.state.email} placeholder="Enter email" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicPassword" className={showPassword?"":"hide-self"}>
<Form.Label>Password</Form.Label>
<Form.Control type="password" name="password" value={this.state.password} placeholder="<PASSWORD>" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicConfirmPassword" className={showConfirmPassword ? "" : "hide-self"}>
<Form.Label>Confirm Password</Form.Label>
<Form.Control type="<PASSWORD>" name="confirmPassword" value={this.state.confirmPassword} placeholder="<PASSWORD>" onChange={this.handleInputChange} />
</Form.Group>
</Form>
<span className={this.state.error?"text-danger":"text-success"}>{this.state.message}</span>
<ButtonToolbar className="justify-content-center">
<Button
variant="danger"
disabled={this.state.isLoading}
className={showBtnSignIn ? "" : "hide-self"}
block
onClick={!this.state.isLoading ? this.authenticate : null}
>
Sign In
</Button>
<Button
variant="danger"
disabled={this.state.isLoading}
className={showBtnSignUp ? "" : "hide-self"}
block
onClick={!this.state.isLoading ? this.signUp : null}
>
Sign Up
</Button>
<Button
variant="danger"
disabled={this.state.isLoading}
className={showBtnReset ? "" : "hide-self"}
block
onClick={!this.state.isLoading ? this.resetPassword : null}
>
Reset Password
</Button>
</ButtonToolbar>
<ButtonToolbar className="justify-content-center">
<Button variant="link" onClick={this.signUpForm} className={showLinkSignUp?"":"hide-self"}>Create an account</Button>
<Button variant="link" onClick={this.signInForm} className={showLinkSignIn?"":"hide-self"}>Sign In</Button>
<Button variant="link" onClick={this.resetPasswordForm} className={showLinkReset?"":"hide-self"}>Forgot password</Button>
</ButtonToolbar>
</Modal.Body>
</Modal>
);
}
}
export default AuthModal;<file_sep>/client/src/pages/Home/index.jsx
import React from 'react';
import API from '../../utils/API';
import Jumbotron from "../../components/Jumbotron";
import PageContainer from '../../components/PageContainer';
import CategoryList from './CategoryList';
class Home extends React.Component {
mounted = false;
state = {
search: "",
postalCode: "",
latitude: "",
longitude: "",
services: [],
categories: [],
notFoundMsg: "",
showingAllCategories: false,
skills: []
}
componentDidMount = () => {
this.mounted = true;
this.searchCategories(false);
API.allSkills()
.then(res => this.setState({ skills: res.data }))
.catch(err => console.log(err));
this.getPostalCodeFromGps();
}
componentWillUnmount() {
this.mounted = false;
}
searchCategories = nolimit => {
API.getCategoriesMostAvailable(nolimit)
.then(res => {
if (this.mounted) {
this.setState({ categories: res.data, showingAllCategories: nolimit });
}
})
.catch(err => console.log(err.response));
}
onSubmit = event => {
event.preventDefault();
this.props.history.push(`search/?search=${this.state.search}&postal=${this.state.postalCode}&lat=${this.state.latitude}&lng=${this.state.longitude}`);
}
handleInputChange = event => {
const { name, value } = event.target;
//if a new postal code is informed then it cleans the geo location
if (name === "postalCode") {
this.setState({ [name]: value, latitude: "", longitude: "" });
}
else {
this.setState({ [name]: value });
}
}
pullAllCategories = () => {
this.searchCategories(true);
}
getPostalCodeFromGps = () => {
//checks whether the browser supports geolocation
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(position => {
API.getPostalCodeFromGeoLocation(position.coords)
.then(res => {
if (this.mounted) {
this.setState({
postalCode: res.data[0].long_name,
latitude: position.coords.latitude,
longitude: position.coords.longitude
});
}
})
.catch(err => {
if (this.mounted) {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude
});
}
console.log(err);
});
});
} else {
console.log("Geolocation is not supported by this browser.");
}
}
render() {
return (
<>
<Jumbotron />
<PageContainer title="Search Professionals">
<form onSubmit={this.onSubmit}>
<div className="search-box">
<input
name="search"
type="text"
className="search"
placeholder="What kind of service are you looking for?"
aria-label="Search"
aria-describedby="btn-search"
autoComplete="off"
list="skills"
onChange={this.handleInputChange}
/>
<span className="divider">
<i className="fas fa-map-marker-alt" title="Get current location" onClick={this.getPostalCodeFromGps}></i>
</span>
<input
name="postalCode"
type="text"
className="postal"
placeholder="Postal Code"
autoComplete="off"
maxLength="7"
value={this.state.postalCode}
onChange={this.handleInputChange}
/>
<button
type="submit"
className="btn btn-secondary"
id="btn-search"
>
<i className="fas fa-search"></i>
</button>
</div>
</form>
<datalist id="skills">
{this.state.skills.map(skill => (
<option value={skill.name} key={skill.id} />
))}
</datalist>
{this.state.categories.length > 0 ?
<CategoryList categories={this.state.categories} pullAllCategories={this.pullAllCategories} showingAllCategories={this.state.showingAllCategories} />
: null
}
</PageContainer>
</>
);
}
}
export default Home;<file_sep>/routes/api/contact.js
const router = require("express").Router();
const contactController = require("../../controllers/contactController");
// Matches with "/api/contact"
router.route("/").get(contactController.findUserRequests);
// Matches with "/api/contact/clients"
router.route("/clients").get(contactController.findUserClients);
// Matches with "/api/contact/skill"
router.route("/skill").post(contactController.create);
// Matches with "/api/contact/skill/:id"
router.route("/skill/:id").get(contactController.findOneBySkill);
// Matches with "/api/contact/chat
router.route("/chat").put(contactController.update);
module.exports = router;<file_sep>/utils/geo.js
require("dotenv").config();
const axios = require("axios");
const googleApiKey = process.env.GOOGLE_API_KEY;
const getPostalCode = function (pos) {
return axios({
method: 'get',
url: 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + pos.lat + ',' + pos.lng + '&key=' + googleApiKey,
responseType: 'json'
});
};
const zipToGeo = function (postal) {
return axios({
method: 'get',
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=' + postal + '&key=' + googleApiKey,
responseType: 'json'
});
}
function degToRadians(degree) {
var rad = degree * (Math.PI / 180);
return rad;
}
function getStraightDistance(posOrigin, posDestination) {
const radius = 6371;
var dLat = degToRadians(posDestination.latitude - posOrigin.latitude);
var dLng = degToRadians(posDestination.longitude - posOrigin.longitude);
a = Math.pow(Math.sin(dLat / 2), 2) +
Math.cos(degToRadians(posOrigin.latitude)) *
Math.cos(degToRadians(posDestination.latitude)) *
Math.pow(Math.sin(dLng / 2), 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
d = radius * c;
return d;
}
module.exports = {
zipToGeo: zipToGeo,
getPostalCode: getPostalCode,
getStraightDistance: getStraightDistance
};
// MAP FEATURE (TBD)
/*function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 43.65, lng: -79.38 },
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
setPlaceMap();
}
function setPlaceMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
let pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
getPostalCode(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
function drawCircle(pos, rad) {
var skillsRadiusCircle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
center: {
lat: pos.lat,
lng: pos.lng
},
radius: rad * 1000
});
map.fitBounds(skillsRadiusCircle.getBounds());
}*/<file_sep>/routes/api/google.js
const router = require("express").Router();
const geoController = require("../../controllers/geoController");
// Matches with "/api/google/postalcode/:latitude/:longitude"
router.route("/postalcode/:latitude/:longitude").get(geoController.getPostalCodeFromGeoLocation);
module.exports = router;<file_sep>/models/contact.js
const Utils = require("../utils/functions");
module.exports = function (sequelize, DataTypes) {
let Contact = sequelize.define("Contact", {
dealClosed: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
dealStatus: {
type: DataTypes.CHAR,
defaultValue: "O" //[O]pened - [P]ending -[D]enied - [C]losed
},
agreedDate: {
type: DataTypes.DATE,
allowNull: true
},
dealDate: {
type: DataTypes.DATE,
allowNull: true
},
note: {
type: DataTypes.TEXT,
allowNull: true
},
price: {
type: DataTypes.STRING,
allowNull: true
},
priceType: {
type: DataTypes.CHAR,
allowNull: true
},
chat: {
type: DataTypes.TEXT,
allowNull: true
},
active: {
type: DataTypes.BOOLEAN,
defaultValue: true
}
},
{
freezeTableName: true,
hooks: {
beforeCreate: function(contact) {
const Skill = this.sequelize.models.Skill;
//get the skills info to update Contact
return Skill.findByPk(contact.SkillId).then(skill => {
contact.price = skill.price;
contact.priceType = skill.priceType;
}).catch(err => console.log(err));
},
afterCreate: function (contact) {
const Skill = this.sequelize.models.Skill;
//send email to provider
return Skill.findOne({
include: [{ all: true }],
where: { id: contact.SkillId }
}).then(skill => {
let chat = JSON.parse(contact.chat);
let htmlBody = `Hello ${skill.User.firstName},
<p>You have a new message from ${chat[0].user} regards to your skill "${skill.name}".</p>
<p>Please visit the website skillshub.heroku.com, on your clients page to see more details.</p>
<p>Skillshub Team</p>`;
let subject = `Skillshub - New Contact from ${chat[0].user}`;
Utils.sendEmail(skill.User.email, subject, htmlBody);
}).catch(err => console.log(err));
}
}
});
Contact.associate = function (models) {
Contact.belongsTo(models.User, {
foreignKey: {
allowNull: false
}
});
Contact.belongsTo(models.Skill, {
foreignKey: {
allowNull: false
}
});
};
return Contact;
};
<file_sep>/database/seeds.sql
/*Automatic execution when the server starts up on the development enviroment */
-- /*test data*/
INSERT INTO User
(id,firstName,lastName,email,password,zipCode,image)
VALUES
(1, 'Carol', 'Cavalcanti', '<EMAIL>', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', 'M4Y1H5', 'profile_1.jpg'),
(2, 'John', 'Doe', 'user1', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'profile_2.jpg'),
(3, 'Mary', 'Jane', 'user2', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'profile_3.jpg'),
(4, 'Frank', 'Russel', 'user3', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'profile_4.jpg'),
(5, 'Maggie', 'MacVey', '<EMAIL>', '$2b$10$odgCqiMprJfgLJPGXiLS4eCbr0dQYXIVSuxFHsZT76ismKyzyXfiy', null, 'profile_5.jpg' ),
(6, 'Angie', 'Dob', 'user4', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'angieprofile.jpg'),
(7, 'Jenn', 'Siggy', 'user5', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'jennprofile.jpg'),
(8, 'Jeremy', 'Delzo', 'user6', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'jeremyprofile.jpg'),
(9, 'Sam', 'McK', 'user7', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'samprofile.jpg'),
(10, 'Amanda', 'Dob', 'user8', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'amandaprofile.jpg'),
(11, 'Matty', 'Bort', 'user9', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'mattprofile.jpg'),
(12, 'Andy', 'Jam', 'user10', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'andyprofile.jpg'),
(13, 'Jordan', 'Caddle', 'user11', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'jordanprofile.jpg'),
(14, 'Andrew', 'Harden', 'user12', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'hardyprofile.jpg'),
(15, 'Emily', 'Lem', 'user13', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'emilyprofile.jpg'),
(16, 'Rachael', 'G', 'user14', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'rachaelprofile.jpg'),
(17, 'Alex', 'Alto', 'user15', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'alexprofile.jpg'),
(18, 'Robyn', 'Bird', 'user16', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'robynprofile.jpg'),
(19, 'Anna', 'Jan', 'user17', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'annaprofile.jpg'),
(20, 'Veronika', 'Trolley', 'user18', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'veronikaprofile.jpg'),
(21, 'Alexis', 'Amb', 'user19', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'alexisprofile.jpg'),
(22, 'Jay', 'Beach', 'user20', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'jayprofile.jpg'),
(23, 'Kallvis', 'Sew', 'user21', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'kallvisprofile.jpg'),
(24, 'Julien', 'Craig', 'user22', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'julienprofile.jpg'),
(25, 'Jorge', 'Mex', 'user23', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'jorgeprofile.jpg'),
(26, 'Kevin', 'Kevon', 'user24', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'kevinprofile.jpg'),
(27, 'Melissa', 'Lima', 'user25', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'melissaprofile.jpg'),
(28, 'Mike', 'Carlo', 'user26', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'mikeprofile.jpg'),
(29, 'Stefanie', 'Barr', 'user27', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'stefanieprofile.jpg'),
(30, 'Phoenix', 'Pink', 'user28', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'phoenixprofile.jpg'),
(31, 'Sandra', 'Rose', 'user29', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'sandraprofile.jpg'),
(32, 'Tara', 'Wells', 'user30', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'taraprofile.jpg'),
(33, 'Wade', 'Edmon', 'user31', '$2b$10$fo85sCgXJsNGGC0Sk28d/u5j7TmmjyxgVbETTYzKwKOAEFobJD8Ra', null, 'wadeprofile.jpg');
INSERT INTO Category
(id, name, image)
VALUES
(1, 'Handy Work', 'handyman.jpg'),
(2, 'Home Reno', 'construction.jpg'),
(3, 'Technology', 'technology.jpg'),
(4, 'DIY & Arts and Crafts', 'DIY.jpg'),
(5, 'Coaching', 'coaching.jpg'),
(6, 'Language', 'translation.jpg'),
(7, 'Education', 'education.jpg'),
(8, 'Misc. Errands', 'errands.jpg'),
(9, 'Childcare', 'childcare.jpg'),
(10, 'Supernatural Services', 'psychic.jpg'),
(11, 'Cleaning', 'cleaning.jpg'),
(12, 'Pet Care', 'pet.jpg'),
(13, 'Cooking', 'cooking.jpg'),
(14, 'Health & Fitness', 'health.jpg'),
(15, 'Beauty', 'beauty.jpg'),
(16, 'Alterations & Tailoring', 'tailoring.jpg'),
(17, 'Auto Services', 'mechanic.jpg'),
(18, 'Landscaping', 'landscaping.jpg');
INSERT INTO Skill
(id,name,description,price,pricetype,zipcode,CategoryId,UserId,score,latitude,longitude)
VALUES
(1, 'roofing', 'With winter coming we all need to make sure that our roofs are winter and spring ready! We have 15 year years experience, we do shingles, steel, and clay roofs. Contact us for pricing! ', 100, 'J', 'M4Y1H5', 2, 1, 3,43.666577, -79.379094),
(2, 'accounting', 'INCOME TAX -From $19.99, Corporate Tax form $100, Business from $50, E-FILE, PERSONAL TAX and CORPORATE TAX RETURNS BUSINESS, SELF EMPLOYED RETURNS FROM $ 50, DISABILITY TAX CREDIT APPLICATION LAST 10 YEARS TAX CAN FILE MAXIMUM REFUND GUARANTEE We Specialize in: . Corporate & Personal Tax Retunes E-File . Accounting & Payroll Services . Prepare T4, T4a & Summary E-File to CRA . Business Plan . Business Registration . CRA Tax Audit Representation . Dissolve Corporation . QUALITY SERVICES WITH ...', 50, 'H', 'M4Y1H5', 4, 2, 2,43.666577, -79.379094),
(3, 'Math Tutor', 'I am a second year commerce student at Ryerson University that specializes in financial math and english. I can help with all levels of math. $25/hour for Grades 1-5, $30/hour for Grades 6-8 and $40/hour for Grades 9-', 10.5, 'H', 'M4Y1H5', 1, 2, 5,43.666577, -79.379094),
(4, 'translating', 'Need Help in Chinese Learning? Experienced teacher offering Adult & Children Classes!
We guarantee your progress! Please feel free to call. TEACHERS QUALIFICATIONS/SKILLS
Over 5 years experience of university teaching
Excellent skills interpersonal communication
Rich experience in teaching Chinese in Canada
Bilingual – Fluent in English and Mandarin
Certified in Teaching Chinese as a Second Language
Superior professional work ethic & self reliance', 500, 'D', 'M4Y1H5', 6, 2, 2,43.666577, -79.379094),
(5, 'Back-end developer', 'I am Experienced It Proffessional. I Have More Than 2 Years Of Experience In It Industry. I Worked on Salesforce, Java, Node Js And Some Other Front End Technology. I did 6 Projects Throughout this Journey. I am About To Finish My Diploma In Web Design And Already Finished My Batchelor Of Computer. If Anyone Has Any Part Time Or Internship Position Available Please Let Me Know.thank You', 90.50, 'H', 'M4Y1H5', 3, 1, 0,43.666577, -79.379094),
(6, 'mechanic', 'Services include:
Pre purchase vehicle Inspections
Timing belt replacement
Brake Replacement
Complete tune ups
Suspension repair
Engine diagnostics and repair
Electrical Repair
Battery, Alternator and Starter replacement
Tire repair and On Rim Tire Change Overs', 60, 'J', 'M4Y1H5', 8, 1, 4,43.666577, -79.379094),
(7, 'flooring', 'Im an experienced carpet and flooring contractor with many years in the trade, covering both the COMMERCIAL & RESIDENTIAL aspects of the business.
Our goal is to offer you the highest levels of service and the best range of quality workmanship and affordable material, all for the most reasonable price possible.', 20, 'J', 'M4Y1H5', 2, 1, 0,43.666577, -79.379094),
(8, 'law', 'WE HAVE OVER A DECADE OF EXPERIENCE DEFENDING CLIENTS THROUGHOUT SOUTHERN ONTARIO. WE ONLY PRACTICE CRIMINAL LAW. If you have been arrested or are being investigated by law enforcement, your freedom and reputation are potentially in jeopardy. With so much at stake, your choice of defense attorney is one of the most critical decisions you will ever make. You need a dedicated and experienced professional with a versatile set of skills.', 450.80, 'H', 'M4Y1H5', 5, 1, 0,43.666577, -79.379094),
(9, 'cleaning', '****FREE QUOTE AND CONSULTATION****
The best price for complete cleaning and maintenance:
-Office Buildings
-Medical/Dental Offices
-Restaurants
-Shopping Malls/Retail Factories
-Factories/Warehouses
-Residential Properties
-Floor (Strip/Refinish)
-Carpet Cleaning
-Construction/Renovation', 250, 'D', 'M4Y1H5', 1, 2, 2,43.666577, -79.379094),
(10, 'dance teacher', 'Looking to learn a Bollywood number to surprise your friends and family at your next event? Or maybe looking for choreography to your first dance?
We provide Bollywood dance choreography for all levels. We can either come to your place or you can come to one of our studio spaces in Mississauga.', 20, 'D', 'M4Y1H5', 4, 1, 2,43.666577, -79.379094),
(11, 'painting', 'Looking to paint a small room or the whole house? Tired of getting outrageous quotes? Professional house painter here with over 15 years experience… Feel free to contact me at anytime', 160, 'J', 'M4Y1H5', 2, 1, 1,43.666577, -79.379094),
(12, 'Plumber', 'PLUMBING - DRAIN SEWER SERVICES :
Brampton Nobleton Mississauga Oakville Toronto Milton scarborough markham richmond hill woodbrdige aurora newmarket north york caledon bolton vaughan georgetown aurora
Emergency Licensed Plumbers 24/7', 45.50, 'H', 'M4Y1H5', 2, 6, 2,43.666577, -79.379094),
(13, 'Front-end Developer', 'Web developer with 3 years experience, comfortable with most front-end technologies.', 27, 'H', 'M4Y1H5', 3, 7, 1,43.666577, -79.379094),
(14, 'Clay pot Making', 'Ever wish for a streaming service with how-to clay videos taught by professional artists? Youve got it with CLAYflicks. Check out our free trial offer! 24/7. The best clay instruction. CLAYflicks. Courses: Wheel Throwing, Handbuilding Pottery, Glazing Pottery', 60, 'J', 'M4Y1H5', 4, 8, 2,43.666577, -79.379094),
(15, 'Life Coach', 'Looking for a life coach/support system?
Are you feeling down about life and just lost? Are you ready to transform your health and life?
Would you like to gain energy, confidence and bring that smile back to your face?
Were here to help!
Ill work one on one with you sending positive and inspirational words your way that will get you back on your feet with a positive breakthrough!
Send us a message and we will be more than happy to help you out!', 150, 'D', 'M4Y1H5', 5, 9, 4,43.666577, -79.379094),
(16, 'Learn Spanish', 'Native spanish speaker who is fluent in english seeking to help you learn some spanish', 20, 'H', 'M4Y1H5', 6, 10, 1,43.666577, -79.379094),
(17, 'Math Tutor', 'Providing Math tutoring for students form grade 8 to 12', 40, 'H', 'M4Y1H5', 7, 11, 0,43.666577, -79.379094),
(18, 'Errand Runner', 'Busy? I can run those pesky errands that you have dreading for you!', 15, 'H', 'M4Y1H5', 8, 12, 0,43.666577, -79.379094),
(19, 'Home Daycare', 'Soon to be licensed with Building Opportunities Home Child Care Agency
SMOKE FREE HOME
CPR & FIRST AID TRAINED PROVIDER
PLANNED PROGRAM
2 SNACKS 1 LUNCH
HOME FOLLOWS ALL PROVINCIAL HEALTH & SAFETY STANDARDS
SPACIOUS BACKYARD
2-3 UNANNOUNCED VISITS BY THE AGENCY
SLEEP ROOM IS LOCATED ON MAIN FLOOR', 60, 'D', 'M4Y1H5', 9, 13, 0,43.666577, -79.379094),
(20, 'Psychic', 'PSYCHIC READINGS
Text -$25
Phone $50
Email $45
In person $90
I make Anulets to attract money,prosperity,success and wealth
I make guard rings to protect you from envy,hex,bad luck ,curses,and more
For help with job,curses or hexes,bad luck,Santeria, witchcraft, voodoo, obeah, and more
Contact mother lola via text,email, or phone', 40, 'J', 'M4Y1H5', 10, 14, 2,43.666577, -79.379094),
(21, 'Home Cleaning', 'I prefrom all house cleaning duties, I am highly detailed oriented', 15, 'H', 'M4Y1H5', 11, 15, 1,43.666577, -79.379094),
(22, 'Dog Walker', 'Lovely weather, isnt it?
If youd prefer not to slip and slide around the corners, or cant make it home for lunch - let me know and i will walk your pup for you.
Have experience with large breeds, senior dogs, puppies and used to walk "troubled" dogs for the Mississauga Humane society.
One on one walks, unless requested otherwise.', 50, 'H', 'M4Y1H5', 12, 16, 5,43.666577, -79.379094),
(23, 'Meal Planner', 'Simplify Meal Planning With Custom Recipes & Easy Grocery Lists To Help You Eat Better. 10-Day Free Trial. Optional Grocery Delivery. Save Time & Reduce Waste. Types: Batch Cooking, Low Carb,, Weight Loss, Clean Eating, Plant-Based, Keto, Paleo.
See How It Works
What Sets Us Apart', 400, 'J', 'M4Y1H5', 13, 17, 2,43.666577, -79.379094),
(24, 'Personal Trainer', 'I can help you achieve your fitness goals. I have 5 years of expierence in creating and designing personalized work outs.', 30, 'H', 'M4Y1H5', 14, 18, 0,43.666577, -79.379094),
(25, 'Nail technician', 'WEDDING PARTY, BIRTHDAYS, Any SPECIAL DAY or "JUST BECAUSE...." Etc...
Private Home Studio Salon
* Skilled Licensed Nail Technician *
*** Nails Nails Nails ***
Classic Manicure
Coloured Acrylic,
Nail Art / Nail Design / Nail w/Gems
Ombre, Glow in the Dark
Custom Design, Infuzed, encapsulated
Etc...', 40, 'H', 'M4Y1H5', 15, 19, 0,43.666577, -79.379094),
(26, 'Dress alterations', 'I have 15 years of clothes alterations and specialize in wedding dresses alterations', 600, 'J', 'M4Y1H5', 16, 20, 2,43.666577, -79.379094),
(27, 'Tire Services', 'Need tire care and no time to deal with it? I provide mobile tire care services!', 55, 'H', 'M4Y1H5', 17, 21, 3,43.666577, -79.379094),
(28, 'Lawn Care', 'We have availability to help you with your residential / commercial FALL and WINTER maintenance needs!
Be sure to have your yard professionally CLEANED and CLEARED of all your FALL LEAF and TREE DEBRIS!!
We understand and know how to properly CUTBACK your PERENNIALS so they BLOOM PERFECTLY next spring!
Hydrangeas, Hostas, Begonias, Peony, Ornamental Grasses we have the skills to prune trim and cut back each properly!
Quote:', 30, 'H', 'M4Y1H5', 18, 22, 2,43.666577, -79.379094),
(29, 'Handy man', 'Handyman:
Maintenance & Improvement
House, Condo, Offices
Painting Indoor & External
Doors and locks, hardware, repairs and installation, trims, baseboard, crown molding, wainscotting, columns,
archways and all carpentry works, shelves and closet design.
Flooring, Stairs, Railings
Ceiling popcorn removal, plastering
Lights fixture, chandeliers, switches, plugs, fans, pot lights....etc.', 25, 'H', 'M4Y1H5', 1, 23, 3,43.666577, -79.379094),
(30, 'Electrician', 'Licensed and insured with over 28 years
of experience, I am offering a wide variety of residential and commercial services as:
-generators hook-up ;
-panels upgrade; wiring and rewiring new and old houses;
-changing panels from fuses to breakers
-installing transformers,
-hot tubs hook-up, swimming pools and jacuzzi;
-pot lights, chandeliers, soffit light,
-audio-video, speakers, home theatre, phone and TVs
-trouble-shooting any electrical problem', 45, 'H', 'M4Y1H5', 2, 24, 0,43.666577, -79.379094),
(31, 'Full Stack Developer', 'Are you looking to develop a reliable and user-friendly web/mobile app at a low cost?
Are you looking to hire a team of developers at a rate less than hiring a person?
If yes, we are here to help.', 50, 'H', 'M4Y1H5', 4, 25, 0,43.666577, -79.379094),
(32, 'Vocal Coach', 'If Singing Is Your Passion, Dont Let It Go! Register To Audition For Frozen Jr. Today! Professional Training And Production. Make Friends And Build Confidence. Unmatched Training. Industry Professionals. Multiple Casts. Many Leading Roles. Services: Singing, Acting, Dancing, Musical Theatre', 55, 'H', 'M4Y1H5', 5, 26, 2,43.666577, -79.379094),
(33, 'Learn French', 'Bonjour ! Learning French Can be fun and exciting ! Learn Parisian French with an experienced , professional and knowledgeable teacher from France : Nicolas !
Available for all levels, adults and children, Nicolas is offering private , group lessons or simply conversational French. He is as well very familiar with the needs of children in immersion programs.', 25, 'H', 'M4Y1H5', 6, 27, 3,43.666577, -79.379094),
(34, 'Essay writing help', 'Quality Eassy Help with Guaranteed Grade As
Hello, I am offering you the best of the best quality writing services. This I offer according to your budget with around the clock customer service support. Do you have an urgent project? Are you stuck with your project? I am more than ready to assist you with your project. I am a proficient Finance graduate, editor, academic writer, and researcher with over six years writing experience.', 60, 'H', 'M4Y1H5', 7, 28, 2,43.666577, -79.379094),
(35, 'Taroat card reading', 'Best Indian Astrologer, Black Magic Removal, Love Spell Caster, Spiritual Healer, Tarot Card Reader, Numerology, Psychic Reading , Clairvoyant, Black Magic Specialist -', 42, 'H', 'M4Y1H5', 10, 29, 2,43.666577, -79.379094),
(36, 'Mobile pet groomers', 'Welcome to mutt cutts, we come to you and!', 150, 'j', 'M4Y1H5', 12, 30, 2,43.666577, -79.379094),
(37, 'Nutritionist', 'Have speacial dietary needs, need help knowing how to cope and what to eat. let me help you! ', 200, 'j', 'M4Y1H5', 14, 31, 2,43.666577, -79.379094),
(38, 'Mobile car detailing ', 'We do mobile detailing Weather permitted at an extra charge of $15 . If you bring your car to the shop full car detail will cost you $75-$95 ( depending on the size of your vehicle) call to book an appointment full car detailing includes:
Interior shampooing
Remove floor salt
Remove stain
Shampoo seats and floors
Leather protection
Wash and dry
Engine shampooing
Rims and tire dressing
Door frames', 200, 'j', 'M4Y1H5', 17, 32, 3,43.666577, -79.379094),
(39, 'Eye Lash Technician', '*** CLASSIC | VOLUME | HYBRID ***
Located in Mississauga, I specialize in the application of EYE LASH EXTENSIONS & EYE LASH LIFT.
Certified LASH TECH, my mission is to provide my clients with stunning lashes customized for your unique eyes. Serviced exclusively by a licensed technician dedicated to extending your lashes and maintaining the health of your natural lashes by proper lash placement and lash care education.', 300, 'j', 'M4Y1H5', 15, 33, 2,43.666577, -79.379094),
(40, 'roofing', 'Weve been providing roofing services for many years.
We provide:
-Re-roofing & Repair( Shingled & Flat )
-Soffit, Fascia, Eavestroughs & downspouts
-Siding
-Skylight Installation and Repair
∙Friendly and Courteous Reception
∙Prompt Service
∙Good reputation
∙Quality work
∙Warranty on all finished work
∙15 years labour warranty
∙Prompt return on all call backs
∙24 hour Emergency repair service', 100, 'J', 'M4C1H5', 2, 1, 3,43.686347, -79.307168),
(41, 'accounting', 'skilled accounter comes and teaches all you need to manage your business', 50, 'H', 'M4R1H5', 4, 2, 2,43.710857, -79.410157),
(42, 'teaching', 'With musical knowledge spanning across many genres, Andrew offers structured and relatable lesson content that inspires and motivates his students to practice. With over a decades worth of teaching experience, Andrew combines his passion for learning, classical music and music technology into every lesson.', 10.5, 'H', 'M4N1H5', 1, 3, 5,43.722223, -79.392652),
(43, 'translating', 'My name is Inaza and I am a professional french translator (English-French) from Toronto who also offers French proofreading services. Competitive rates for editing and French proofreading services.', 500, 'D', 'M4T1H5', 6, 4, 3,43.689468, -79.385609),
(44, 'developer', 'Im an experienced mobile and web app developer. If you have a good idea or an existing project that needs to be complete, please give me a call.', 90.50, 'H', 'M4A1T5', 3, 5, 2,43.735973, -79.311774),
(45, 'mechanic', 'I come to your house and fix your vehicles
I am a apprentice mechanic looking for work
I come and change your snow tires in your driveway save you the hassle of lugging tires around and waiting for appointments
Brakes
Body work
Change tires
Oil changes
Wheel bearrings
And much more
Please contact for any inquiry
Thanks', 60, 'J', 'M5Y1H5', 8, 6, 4,43.666438, -79.378894),
(46, 'flooring', 'If you are looking to get your flooring installed you came to the right place, I can assure you we are the best at what we do and we back that up with a 1 year workmanship guarantee. We are professional installers who are fully insured and take great pride in all of our work. Do not hesitate to call for any questions or for a Free Estimate', 20, 'J', 'M4K1H5', 2, 7, 2,43.672543, -79.351783),
(47, 'law', 'WE ONLY PRACTICE FAMILY LAW AND CRIMINAL LAW:
Family law handles domestic matters involving partners, spouses, and children. Review the major legal issues related to family law, and learn how a family law attorney can help. We handle each Family Law case with compassion. The best interest of your children is our #1 priority. We specialize in the following:
-Divorce Contested/Uncontested
-Child Custody Access Rights
-Spousal Support Child Support', 450.80, 'H', 'M4C1L5', 5, 8, 2,43.688250, -79.300669),
(48, 'cleaning', 'I have a cleaning business I will clean your house at any time of the day. Ima available 7days a week. I live Scarborough , and will work around Scarborough. Any more information please call for inquiries!', 250, 'D', 'M4M1H5', 1, 9, 1,43.659323, -79.347036),
(49, 'dancing', 'Im looking for male or female those interested to learn Salsa dancing. Age group around 45 to 60 years.
It is in Mississauga, $10/- for a class. It is on Thursday and Friday...After 7.30 onward....Interested contact with your cell number ASAP.', 20, 'D', 'M4M1H5', 4, 10, 2,43.659323, -79.347036),
(50, 'painting', 'We are WSIB Compliant, have $5 million liability insurance, are CERTIFIED PAINTERS.
From older houses that require plastering, to new custom builds. We do it all. We are punctual, clean, and professional.
How does it work?
1. We provide you with a quote and timeline to start project, once agreed, you make paint colour selection.
2. We come on the day agreed upon, completely cover the work area, and finish the project with a crew of professional painters.
3. Upon completion, we tidy up the area and leave the work area nice and clean.
We do not just paint your walls, we also fix cracks and holes, sand it and use only PREMIUM VOC-Free acrylic paint.
We can spray paint, stain, varnish, seal, roll, and have superior straight edge brush cutting. We also provide exterior painting services.', 160, 'J', 'M4Y1L5', 2, 11, 2,43.667362, -79.383183),
(51, 'Plumber', 'Plumber Licensed & Insured
Commerical and Residential
OUR SERVICES
We provide Plumbing Services
One Year Warranty on All Job
* Specialized Basement Underground Rough in (washroom, laundry, Kicthen, City Inpection no problem)
* Basement Unit Spliter
* Sprinker
* Tank Mixing Valave
* Custom house Plumbing
* Commercial Plumbing job
* New Laundry
* Sump Pump
* Replace copper pipe to pex', 45.50, 'H', 'M4G1H5', 2, 12, 4,43.699965, -79.367561),
(52, 'Front-end Developer', 'Web developer with 3 years experience, comfortable with most front-end technologies.', 27, 'H', 'M4H1H5', 3, 13, 5,43.703538, -79.346935),
(53, 'Clay pot Making', 'Come learn how to make your own custom clay pots', 60, 'J', 'M4H1H5', 4, 14, 5,43.703538, -79.346935),
(54, 'Life Coach', 'Gentlemen!
Do You Want To Improve Your Dating Life And Meet More Women?
Do you want to go on more dates?
Imagine this: You simply walk up to any girl that catches your eye, and youll know exactly what to say. Youll never be at a loss for words, and you wont be nervous. In minutes youll be walking away with her number and a good chance of seeing her later that week, or even later that same night! Let me teach you how.', 150, 'D', 'M4J1H5', 5, 15, 5,43.676779, -79.342361),
(55, 'Learn Spanish', 'Native spanish speaker who is fluent in english seeking to help you learn some spanish', 20, 'H', 'M4K1H5', 6, 16, 3,43.672691, -79.351825),
(56, 'Math Tutor', 'I graduated at the top of the Gifted Education Program in Ontario all through university (U of T Physics).
You will find that Im not your average tutor. Im able to connect with people and explain things MUCH better and simpler. I understand why things seem hard, and I make them easy.
If that is what you are in need of then let me share my gift with you.
Leave a number at which you can be reached.', 40, 'H', 'M4L1H5', 7, 17, 3,43.669308, -79.304559),
(57, 'Errand Runner', 'Busy? I can run those pesky errands that you have dreading for you!', 15, 'H', 'M4L1H5', 8, 18, 2,43.669308, -79.304559),
(58, 'Home Daycare', 'I run a home daycare, I have my ECE license and have 5 years expierence of child care services', 60, 'D', 'M4N1T5', 9, 19, 2,43.727590, -79.389807),
(59, 'Home Daycare', 'I run a home daycare, I have my ECE license and have 5 years expierence of child care services', 60, 'D', 'M4N1T5', 9, 20, 2,43.727590, -79.389807),
(60, 'Psychic', 'Curious about what lies ahead, come and see me so we can discover it', 40, 'J', 'M4C4V4', 10, 33, 1,43.690240, -79.304126),
(61, 'Home Cleaning', 'I prefrom all house cleaning duties, I am highly detailed oriented', 15, 'H', 'M4C4X2', 11, 32, 2,43.687321, -79.300636),
(62, 'Dog Walker', 'I am an animal lover and more specifically a dog lover, so let me walk your dog!', 50, 'H', 'M4C4X2', 12, 31, 2,43.687321, -79.300636),
(63, 'Meal Planner', 'I help design and prepare meal plans for a variety of dietary needs!', 400, 'J', 'M4C4X2', 13, 30, 1,43.687321, -79.300636),
(64, 'Personal Trainer', 'I can help you achieve your fitness goals. I have 5 years of expierence in creating and designing personalized work outs.', 30, 'H', 'M4C4X2', 14, 29, 2,43.687321, -79.300636),
(65, 'Nail technician', 'I am a nail artist, i do acrylic and gel nails', 40, 'H', 'M4C4X2', 15, 28, 2,43.687321, -79.300636),
(66, 'Dress alterations', 'I have 15 years of clothes alterations and specialize in wedding dresses alterations', 600, 'J', 'M4C4X7', 16, 27, 2,43.689894, -79.302995),
(67, 'Tire Services', 'Need tire care and no time to deal with it? I provide mobile tire care services!', 55, 'H', 'M4C4Y4', 17, 26, 4,43.696150, -79.305624),
(68, 'Lawn Care', 'I provide you with all your lawn care needs, will water and treat your lawn for all its needs', 30, 'H', 'M4C4Y5', 18, 25, 1,43.689330, -79.300691),
(69, 'Handy man', 'I provide simple home repairs for a low price!', 25, 'H', 'M4C4Y6', 1, 24, 2,43.689850, -79.300943),
(70, 'Electrician', 'Licensed electrician with 5 years experience.', 45, 'H', 'M4C4Y7', 2, 23, 4,43.690030, -79.301507),
(71, 'Full Stack Developer', 'You can fulfil all of your web design and developments needs.', 50, 'H', 'M4C4Y7', 4, 22, 0,43.690030, -79.301507),
(72, 'Vocal Coach', 'Trained professioanl vocal coach ', 55, 'H', 'M4C4Y7', 5, 21, 3,43.690030, -79.301507),
(73, 'Learn French', 'Let me help you improve your french language skills', 25, 'H', 'M4C4Y7', 6, 20, 1,43.690030, -79.301507),
(74, 'Essay writing help', 'Let me help you write those annoying essays!', 60, 'H', 'M4C4Y7', 7, 19, 2,43.690030, -79.301507),
(75, 'Taroat card reading', 'Dont know what the future has in store for you? Well I do!', 42, 'H', 'M3C0C2', 10, 18, 3,43.724247, -79.350696),
(76, 'Mobile pet groomers', 'Welcome to mutt cutts, we come to you and!', 150, 'j', 'M3C0C2', 12, 17, 3,43.724247, -79.350696),
(77, 'Nutritionist', 'Have speacial dietary needs, need help knowing how to cope and what to eat. let me help you! ', 200, 'j', 'M3C0C2', 14, 16, 1,43.724247, -79.350696),
(78, 'Mobile car detailing ', 'WE come to you and detail your car. We use the safest products that produce teh best results!', 200, 'j', 'M3C0C2', 17, 15, 5,43.724247, -79.350696),
(79, 'Eye Lash Technician', '3 years experience in making your eyes pop!', 300, 'j', 'M3C0C2', 15, 14, 4,43.724247, -79.350696);
INSERT INTO Review
(review,score,UserId,SkillId)
VALUES
('he was late but job was good', 3, 1, 1),
('thank you sir', 3, 1, 1),
('i love this web site', 3, 1, 1),
('amazing job', 5, 2, 3),
('thank you so much', 5, 3, 3),
('i dont know', 2, 4, 2),
('not good', 2, 1, 2),
('wouldnot recomend', 2, 1, 2);<file_sep>/database/schema.sql
-- DROP DATABASE IF EXISTS skillshub;
-- CREATE DATABASE skillshub;
/*
Automatic execution when the server startups:
*/
ALTER TABLE User
CHANGE COLUMN createdAt createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
CHANGE COLUMN updatedAt updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
ALTER TABLE Category
CHANGE COLUMN createdAt createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
CHANGE COLUMN updatedAt updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
ALTER TABLE Skill
CHANGE COLUMN createdAt createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
CHANGE COLUMN updatedAt updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
ALTER TABLE Review
CHANGE COLUMN createdAt createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
CHANGE COLUMN updatedAt updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
ALTER TABLE Contact
CHANGE COLUMN createdAt createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
CHANGE COLUMN updatedAt updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
<file_sep>/README.md
# Skills Hub
Skills Hub is a virtual skill sharing platform. Users who want to share their talents can create a profile and post their shareable skills for hire while users looking for help with a job or chore can categorically search for service offerings, read/post reviews and contact skill sharers about rendering their services. Skills shared can vary from aesthetic services and personal training to home repair offerings and mechanic services. Lastly, Skills Hub users will be asked to rate and review the skill that has been shared with them.
[View Website](https://skillshub.herokuapp.com/)

#### Users
Skills Hub is for skilled people who are looking to provide their services for money. The application provides a platform that connects people with others who are skilled and offering corresponding needs to their own.
#### Example
Skilled user, Dima, is looking to make some spare cash by cleaning cars and advertises on his profile that car detailing is a skill he would like to share. User Maggie has a car but no time to clean it. Maggie goes on Skills Hub and searches “car detailing” and finds Dima’s profile because he lives near her and his rate is reasonable. Maggie reaches out to Dima through the application and they arrange a time for Dima to clean Maggie’s car.
#### Why Choose Skills Hub?
Skills Hub differentiates itself by eliminating the sale of things (as you might see on websites like Kijiji and Craigslist) and specifically helps its users sell their skills and services. The rate and review options helps users - both providing and purchasing - to make an informed choice when choosing a skill sharer.
## Authors
- [<NAME>](https://github.com/candidoregis)
- [<NAME>](https://github.com/carolinapc)
- [<NAME>](https://github.com/Dimakasrelishvili)
- [<NAME>](https://github.com/maggiemac7)
- [<NAME>](https://github.com/nrv0926)
## Techonologies Used
#### Back-end
- Node.js
- Express
- Javascript
- MySQL
- Sequelize
- Socket.io
- Bcrypt
#### Front-end
- React.js
- Bootstrap
#### API's
- Sendgrid
- Google (Geocoding, Geolocation, Maps Javascript)
<file_sep>/client/src/pages/Profile/PersonalInfo.jsx
import React from 'react';
import { Form, Button } from 'react-bootstrap';
import API from '../../utils/API';
class PersonalInfo extends React.Component {
mounted = false;
state = {
firstName: "",
lastName: "",
email: "",
zipCode: "",
message: "",
error: false,
isLoading: false
}
componentDidMount = () => {
this.mounted = true;
//fill all the fields from database
API.getUserAccount().then(res => {
if (res.data) {
if (this.mounted) {
this.setState({
firstName: res.data.firstName,
lastName: res.data.lastName,
email: res.data.email,
zipCode: res.data.zipCode
});
}
}
else {
console.log("User didn't sign in or not found!");
}
}).catch(err => console.log(err));
}
componentWillUnmount() {
this.mounted = false;
}
handleInputChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value });
}
updateInfo = () => {
const { firstName, lastName, email, zipCode } = this.state;
API.updateUser({
firstname: firstName,
lastName: lastName,
email: email,
zipCode: zipCode
})
.then(() => {
this.setState({ message: "Profile info updated successfully", error: false, isLoading: false });
})
.catch(err => {
let message;
if (err.response.data.errors) {
message = err.response.data.errors[0].message;
}
else {
message = err.response.data;
}
this.setState({ message, error: true, isLoading:false });
});
}
render() {
return (
<Form>
<Form.Group controlId="formBasicFirstName">
<Form.Label>First Name</Form.Label>
<Form.Control type="text" name="firstName" value={this.state.firstName} placeholder="Enter first name" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicLastName">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" name="lastName" value={this.state.lastName} placeholder="Enter last name" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" name="email" value={this.state.email} placeholder="Enter email" onChange={this.handleInputChange} />
</Form.Group>
<Form.Group controlId="formBasicZipCode">
<Form.Label>Zip Code</Form.Label>
<Form.Control type="text" name="zipCode" value={this.state.zipCode} placeholder="Zip Code" onChange={this.handleInputChange} />
</Form.Group>
<div className={this.state.error?"text-danger":"text-success"}>{this.state.message}</div>
<Button
variant="secondary"
disabled={this.state.isLoading}
onClick={!this.state.isLoading ? this.updateInfo : null}
className="mt-3"
>
<i className="fas fa-check"></i> Save
</Button>
</Form>
);
}
}
export default PersonalInfo;<file_sep>/client/src/App.js
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";
import API from './utils/API';
import io from "socket.io-client";
import { ToastContainer, toast } from 'react-toastify';
//CSS
import "normalize.css";
import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-toastify/dist/ReactToastify.css';
import "./App.css";
//Stateless Components
import MenuTop from "./components/MenuTop";
import AuthModal from "./components/AuthModal";
import WithAuth from './components/WithAuth';
import Footer from './components/Footer';
//Pages
import Home from "./pages/Home";
import Search from "./pages/Search";
import Profile from "./pages/Profile";
import UserProfile from "./pages/UserProfile";
import Skill from "./pages/Skill";
import Contact from "./pages/Contact";
import About from "./pages/About";
class App extends Component {
mounted = false;
state = {
userData: {},
authenticated: false,
authModalShow: false,
viewType: "signin"
}
componentDidMount = () => {
this.mounted = true;
const socket = io();
socket.on("chat_notification", msg => {
if (msg.userDestinyId === this.state.userData.UserId) {
let notify = `${msg.chat.user} sent a message`;
toast.info(notify,{ position: toast.POSITION.BOTTOM_LEFT });
}
});
socket.on("new_contact_notification", msg => {
if (msg.destinyUserId === this.state.userData.UserId) {
let notify = `You have a new contact from ${msg.originUserName}`;
toast.info(notify, { position: toast.POSITION.BOTTOM_LEFT });
}
});
//check authentication status
API.getUserSession().then(res => {
if (this.mounted) {
if (res.data.loggedin) {
this.setState({
userData: res.data,
authenticated: true
});
}
}
}).catch(err => console.log(err.response.data));
}
//show/hide authentication modal
toggleAuthModalShow = viewType => {
this.setState({
authModalShow: !this.state.authModalShow,
viewType: viewType
});
}
//handle authentication status
handleAuthentication = auth => {
this.setState({
userData: auth.data,
authenticated: true,
authModalShow: false
});
}
handleSignOut = () => {
API.signOut().then(res => {
this.setState({
userData: "",
authenticated: false
})
}).catch(err=>console.log(err.response));
}
render() {
return (
<Router>
<ToastContainer />
<MenuTop
toggleAuthModalShow={this.toggleAuthModalShow}
authenticated={this.state.authenticated}
userInfo={this.state.userData}
signOut={this.handleSignOut}
/>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/search" component={Search} />
<Route exact path="/about" component={About} />
<Route exact path="/skill/:id" render={props => <Skill userData={this.state.userData} toggleAuthModalShow={this.toggleAuthModalShow} {...props} />} />
<Route exact path="/profile" component={WithAuth(Profile)} />
<Route exact path="/profile/:id" component={UserProfile} />
<Route exact path="/contact/:pagetype" component={WithAuth(Contact)} />
<Route exact path="/contact/:pagetype/:id" component={WithAuth(Contact)} />
<Route path="*">
<Redirect to="/" />
</Route>
</Switch>
<AuthModal
handleCloseModal={this.toggleAuthModalShow}
show={this.state.authModalShow}
viewType={this.state.viewType}
handleAuthentication={this.handleAuthentication}
/>
<Footer />
</Router>
);
}
}
export default App;
<file_sep>/client/src/pages/Skill/ContactModal.jsx
import React from 'react';
import { Modal, Button, ButtonToolbar } from 'react-bootstrap';
import Form from 'react-bootstrap/Form';
import API from '../../utils/API';
import "./style.css";
import io from "socket.io-client";
class ContactModal extends React.Component {
state = {
text: "",
error: false,
message: "",
isLoading: false
}
handleInputChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value } );
}
onEnterModal = () => {
this.setState({text: "", error: false, message: "", isLoading: false});
}
submitContact = event => {
event.preventDefault();
this.setState({ error: false, message: "", isLoading: true });
//get the text from the contact modal form
let data = {
SkillId: this.props.skillId,
text: this.state.text.trim()
};
API.createSkillContact(data).then(res => {
const socket = io();
socket.emit("new_contact_created", { destinyUserId: this.props.skillUserId, originUserName: this.props.userData.UserName + " " + this.props.userData.UserLastName });
//redirect to the chat page opened for this new contact created
this.props.history.push(`/contact/request/${res.data.id}`);
}).catch(err => {
if (err.response.data) {
this.setState({ error: true, message: err.response.data, isLoading: false });
}
else {
console.log(err);
}
});
}
render() {
return (
<Modal show={this.props.show} onHide={this.props.handleCloseModal} onEnter={this.onEnterModal}>
<Modal.Header closeButton>
<Modal.Title>Contact</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form.Control as="textarea" rows="5" name="text" value={this.state.text||""} placeholder="Type a message..." onChange={this.handleInputChange} />
<span className={this.state.error?"text-danger":"text-success"}>{this.state.message}</span>
<ButtonToolbar className="justify-content-center">
<Button
variant="primary"
disabled={this.state.isLoading}
className="mr-3 mt-3"
onClick={!this.state.isLoading ? this.submitContact : null}
>
Send
</Button>
<Button
variant="secondary"
onClick={this.props.handleCloseModal}
className="mt-3"
>
Cancel
</Button>
</ButtonToolbar>
</Modal.Body>
</Modal>
);
}
}
export default ContactModal;<file_sep>/client/src/pages/Profile/SkillsList.jsx
import React from 'react';
import { Table, Button, Form } from 'react-bootstrap';
const SkillsList = props => {
return (
<div className="shadow">
<Table responsive striped>
<thead>
<tr>
<th>Skill</th>
<th>Category</th>
<th>Available</th>
<th><Button onClick={props.addSkill} variant="primary"><i className="fas fa-plus"></i> New</Button></th>
</tr>
</thead>
<tbody>
{props.userSkills.map(skill => {
return (
<tr key={skill.id}>
<td>{skill.name}</td>
<td>{skill.Category.name}</td>
<td>
<Form.Check
type="switch"
id={skill.id}
name="active"
value={skill.active}
checked={skill.active}
onChange={props.toogleActive}
label=""
/>
</td>
<td>
<Button onClick={()=>props.editSkill(skill)} variant="secondary"><i className="fas fa-pen"></i> Edit</Button>
</td>
</tr>
);
})}
</tbody>
</Table>
</div>
);
}
export default SkillsList;<file_sep>/client/src/components/MenuTop/index.jsx
import React from "react";
import { NavLink } from "react-router-dom";
import { Navbar, Nav, NavDropdown } from "react-bootstrap";
import "./style.css";
// Depending on the current path, this component sets the "active" class on the appropriate navigation link item
function MenuTop(props) {
return (
<Navbar collapseOnSelect fixed="top" className="shadow" expand="lg" bg="dark" variant="dark">
<Navbar.Brand>
<NavLink
exact
to="/"
activeClassName="active"
className="nav-link"
>
Skills HUB
</NavLink>
</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<NavLink
exact
to="/about"
activeClassName="active"
className="nav-link"
>
About
</NavLink>
<NavLink
exact
to="/search"
activeClassName="active"
className="nav-link"
>
Search
</NavLink>
</Nav>
<Nav>
{/* show buttons according to authentication status */}
{props.authenticated ?
<NavDropdown title={<><i className="fas fa-user"></i> {props.userInfo.UserName}</>} id="basic-nav-dropdown" className="menu-auth">
<NavDropdown.Item href="/contact/request">Your Requests</NavDropdown.Item>
<NavDropdown.Item href="/contact/client">Your Clients</NavDropdown.Item>
<NavDropdown.Item href="/profile">Profile</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item onClick={() => props.signOut()}>Sign-Out</NavDropdown.Item>
</NavDropdown>
:
<>
<Nav.Link className="nav-link" onClick={() => props.toggleAuthModalShow("signin")}>Sign-In</Nav.Link>
<Nav.Link className="nav-link" onClick={() => props.toggleAuthModalShow("signup")}>Sign-Up</Nav.Link>
</>
}
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
export default MenuTop;
<file_sep>/controllers/categoryController.js
const db = require("../models");
// Defining methods for the category
module.exports = {
findAll: function (req, res) {
db.Category
.findAll({order: [['name', 'ASC']]})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
//get categories that have most skills available
findAllGrouped: function (req, res) {
const limit = req.query.nolimit==="true" ? "" : "LIMIT 6";
db.sequelize.query(`
SELECT c.id as id, c.name as name, c.image, count(*) as tot
FROM Category c, Skill s
WHERE s.CategoryId = c.id and s.active = true
GROUP BY c.id, c.name, c.image
ORDER BY 3 DESC
${limit}
`,
{
raw: true,
type: db.Sequelize.QueryTypes.SELECT
})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
}<file_sep>/client/src/pages/Skill/index.jsx
import React from 'react';
import API from '../../utils/API';
import Utils from '../../utils';
import PageContainer from '../../components/PageContainer';
import { Row, Col, Button } from 'react-bootstrap';
import Reviews from './Reviews';
import ReviewForm from './ReviewForm';
import { NavLink } from 'react-router-dom';
import ContactModal from './ContactModal';
class Skill extends React.Component {
mounted = false;
distance = "";
zipCode = "";
state = {
skill: {
id: "",
name: "",
price: "",
priceType: "",
score: 0,
UserId: "",
User: {
firstName: "",
lastName: "",
image: "/profile.jpg"
},
Reviews: []
},
found: false,
contactText: "",
showContactModal: false
};
componentDidMount = () => {
this.mounted = true;
let data = { id: this.props.match.params.id };
let params = new URLSearchParams(this.props.location.search);
this.distance = params.get("dist");
this.zipCode = params.get("zip");
this.getSkillFromDb(data);
}
componentWillUnmount() {
this.mounted = false;
}
getSkillFromDb = data => {
//get skill from database
API.getSkills(data).then(res => {
if (res.data.length > 0) {
this.setState({ skill: res.data[0], found: true });
}
}).catch(err => console.log(err.response));
}
contactHandle = () => {
//checks if the contact is already opened (or still opened)
API.getSkillContact(this.state.skill.id).then(res => {
//if it was found
if (res.data) {
//redirect to the requests page with the opened chat
this.props.history.push(`/contact/request/${res.data.id}`);
}
else {
//opens a modal to create a new contact
this.setState({ showContactModal: true });
}
}).catch(err => console.log(err));
}
closeContactModal = () => this.setState({ showContactModal: false });
handleImgError = () => {
let skill = this.state.skill;
skill.User.image = "profile.jpg";
this.setState({ skill });
}
handleReviewsImgError = reviewId => {
let skill = this.state.skill;
skill.Reviews.map(review => {
if (review.id === reviewId) {
review.User.image = "profile.jpg";
}
return review;
});
this.setState({ skill });
}
getMapLink = () => {
if (this.zipCode) {
return `https://www.google.com.br/maps/dir/${this.zipCode}/${this.state.skill.latitude},${this.state.skill.longitude}`;
}
else {
return `http://www.google.com.br/maps/place/${this.state.skill.latitude},${this.state.skill.longitude}`;
}
}
render() {
const { skill, found } = this.state;
return (
<>
{found?
<PageContainer title="">
<Row className="mt-5">
<Col md="4">
<img src={skill.User.image? `/${skill.User.image}` : "/profile.jpg"} alt="Profile" className="profile-img shadow-lg mb-4" onError={this.handleImgError} />
<h3 className="card-subtitle mb-2 text-muted">{skill.User.firstName + " " + skill.User.lastName}</h3>
<NavLink
exact
to={"/profile/"+skill.UserId}
activeClassName="active"
className="btn btn-secondary mr-3"
>
<i className="far fa-user-circle"></i> View Profile
</NavLink>
{(this.props.userData.loggedin) ?
<Button
className="btn btn-secondary"
onClick={this.contactHandle}
>
<i className="far fa-comments"></i> Contact
</Button>
:
<Button className="btn-danger mr-3" onClick={() => this.props.toggleAuthModalShow("signin")}>Sign-In to Contact</Button>
}
</Col>
<Col md="8" className="pt-3">
<div className="skill-header">
<div>
<h4>{skill.name}</h4>
<h6>
{this.distance ? `${this.distance} km` : null}
<Button variant="outline-secondary" className="ml-3 btn-sm" href={this.getMapLink()} target="_blank">
<i className="far fa-map"></i> View Map
</Button>
</h6>
</div>
<div>
<h4>Price: ${skill.price + " per " + Utils.getPriceTypeName(skill.priceType)}</h4>
<h5 className="stars">{skill.score}.0 {Utils.getStars(skill.score)} ({skill.Reviews.length})</h5>
</div>
</div>
<div className="skill-description">{Utils.replaceNewLines(skill.description)}</div>
</Col>
</Row>
<Row className="border-top mt-4 p-2">
<Col md="4">
{(this.props.userData.loggedin )?
<ReviewForm skillId={skill.id} getSkillFromDb={this.getSkillFromDb} />
:
"Sign in to add a review"
}
</Col>
<Col md="8">
<h3>Reviews</h3>
<Reviews reviews={skill.Reviews} handleReviewsImgError={this.handleReviewsImgError}/>
</Col>
</Row>
</PageContainer>
:
<PageContainer title="Skill was not found!" />
}
<ContactModal
handleCloseModal={this.closeContactModal}
show={this.state.showContactModal}
skillId={skill.id}
skillUserId={skill.UserId}
{...this.props}
/>
</>
);
}
}
export default Skill;<file_sep>/client/src/pages/Skill/Reviews.jsx
import React from 'react';
import { Card } from 'react-bootstrap';
import Utils from '../../utils';
import Moment from 'react-moment';
import './style.css';
const Reviews = props => {
return (
<>
{props.reviews.map(review => {
return (
<Card key={review.id} className="mt-3">
<Card.Header>
<div className="wrap-review-header">
<span>{Utils.getStars(review.score)}</span>
<span><Moment format="YYYY/MM/DD" date={review.createAt} /></span>
</div>
</Card.Header>
<Card.Body>
<blockquote className="blockquote mb-0">
<p>{Utils.replaceNewLines(review.review)}</p>
<footer className="blockquote-footer">
{review.User.firstName + " " + review.User.lastName}
<img src={review.User.image? `/${review.User.image}` : "/profile.jpg"} alt="User" onError={()=>props.handleReviewsImgError(review.id)} />
</footer>
</blockquote>
</Card.Body>
</Card>
);
})}
</>
);
}
export default Reviews;<file_sep>/client/src/pages/Skill/ReviewForm.jsx
import React from 'react';
import { Form, Button } from 'react-bootstrap';
import API from '../../utils/API';
class ReviewForm extends React.Component {
state = {
skillId: this.props.skillId,
review: "",
score: 0,
scoreChosen: false,
loading: false,
message: "",
error: false
}
saveReview = event => {
event.preventDefault();
this.setState({ loading: true });
const data = {
SkillId: this.state.skillId,
score: this.state.score,
review: this.state.review
};
API.addReview(data).then(res => {
this.setState({ loading: false, scoreChosen: false, review: "", score: 0, error: false, message: "Review Sent! Thank you!" });
this.props.getSkillFromDb({ id: res.data.SkillId });
}).catch(err => {
let message = "";
if (err.response.data.errors)
message = err.response.data.errors[0].message;
else
message = "Unexpected error sending review. Please try again.";
this.setState({ loading: false, error: true, message });
console.log("error sending a review");
});
}
handleInputChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value, message: "" });
}
handleMouseOver = event => {
if(!this.state.scoreChosen)
this.setState({ score: event.target.id });
}
handleMouseOut = () => {
if(!this.state.scoreChosen)
this.setState({ score: 0 });
}
handleStarClick = event => {
this.setState({ score: event.target.id, scoreChosen: true });
}
getScoreClass = score => {
if (this.state.score <= score-1) {
return "far";
}
else {
return "fas";
}
}
getStars = ()=>{
let stars = [];
for (let i = 1; i <= 5; i++){
stars.push(<i key={i} className={`${this.getScoreClass(i)} fa-star star`} id={i} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} onClick={this.handleStarClick}></i>);
}
return stars;
}
render() {
return (
<>
<h5>Add Your Review</h5>
<h5>{this.getStars()}</h5>
<Form.Control as="textarea" rows="5" name="review" value={this.state.review} placeholder="Comment your review..." onChange={this.handleInputChange} />
<div className={this.state.error ? "text-danger" : "text-success"}>{this.state.message}</div>
<Button
className="mt-3"
variant="secondary"
disabled={this.state.loading || this.state.review.trim() === ""}
onClick={(!this.state.loading && this.state.review.trim() !== "") ? this.saveReview : null}>Submit</Button>
</>
);
}
}
export default ReviewForm;<file_sep>/controllers/skillController.js
const db = require("../models");
const geo = require("../utils/geo");
//filter results from findAll method by distance
const filterSkillsByDistance = (results, distance, latitude, longitude) => {
distance = parseInt(distance);
let data = results.map(item => {
item.dataValues.distance = geo.getStraightDistance(item.dataValues, { latitude, longitude }).toFixed(2);
return item;
}).filter(item => {
return item.dataValues.distance <= distance;
});
return data;
};
// Defining methods for the booksController
module.exports = {
/*
Gets all skills filtering by category, search text, id, zipCode and distance range
*/
findAll: function (req, res) {
let { search, categoryId, id, zipCode, distanceRange, latitude, longitude } = req.query;
let where = {active: true};
let include = [{ all: true }];
if (id) {
where.id = id;
include = [{ all: true, nested: true }];
}
if (categoryId) {
where.CategoryId = categoryId;
}
if (search) {
where.name = {
[db.Sequelize.Op.like]: [`%${search}%`]
};
}
db.Skill
.findAll({
include: include,
where: where,
order:[['createdAt', 'DESC'],[db.Review,'createdAt','DESC']]
})
.then(data => {
//if zipCode was passed
if (zipCode) {
distanceRange = distanceRange || 5; //default 5km - if the distance ranges wasn't passed
//if geo locattion was passed
if (latitude && longitude) {
//filter the results by distance
res.json(filterSkillsByDistance(data, distanceRange, latitude, longitude));
}
else {
//get lat/lng from zip code
geo.zipToGeo(zipCode).then(resp => {
const { lat, lng } = resp.data.results[0].geometry.location;
//filter the results by distance
res.json(filterSkillsByDistance(data, distanceRange, lat, lng));
}).catch(err => {
console.log("Error at skillController->findAll->zipToGeo:", err);
res.json(data);
});
}
}
else {
res.json(data);
}
})
.catch(err => res.status(422).json(err));
},
addReview: function (req, res) {
//checks if the user is logged in
if (!req.session.loggedin) {
res.status(400).end("You need to sign in to update an user.");
}
else {
req.body.UserId = req.session.UserId;
db.Review.create(req.body)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
},
//get all skills without its relations and no filters
allSkills: function (req, res) {
db.Skill.findAll()
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
}<file_sep>/models/review.js
module.exports = function (sequelize, DataTypes) {
let Review = sequelize.define("Review", {
review: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [3, 500],
msg: "User review must have at least 3 and max 500 characters"
}
}
},
score: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
}
},
{
freezeTableName: true,
hooks: {
afterCreate: function (review) {
let Skill = this.sequelize.models.Skill;
Review.count({ where: { SkillId: review.SkillId } }).then(tot => {
Review.sum("score", { where: { SkillId: review.SkillId } }).then(sum => {
let skillScore = Math.round(sum / tot);
//update the skill score
Skill.update({
score: skillScore
},
{
where: { id: review.SkillId }
}).then(() => {
console.log("Skill score was updated!");
});
});
});
}
}
});
Review.associate = function (models) {
Review.belongsTo(models.User, {
foreignKey: {
allowNull: false
}
});
Review.belongsTo(models.Skill, {
foreignKey: {
allowNull: false
}
});
};
return Review;
};
<file_sep>/client/src/pages/Contact/index.jsx
import React from 'react';
import PageContainer from '../../components/PageContainer';
import ContactDetail from './ContactDetail';
import Chat from '../../components/Chat';
import { ListGroup, Row, Col } from 'react-bootstrap';
import API from '../../utils/API';
import Utils from '../../utils';
import Moment from 'moment';
import io from "socket.io-client";
class Contact extends React.Component {
constructor(props) {
super(props);
//ref fields to handle
this.refChatScreen = React.createRef();
this.refChatText = React.createRef();
this.mounted = false;
this.pageType = "";
this.state = {
pageType: "",
currentContact: {},
contacts: [],
text: "",
note: "",
loading: false,
loadingDetails: false
};
this.socket = io();
//update all contacts if a new contact was created
this.socket.on("new_contact_notification", msg => {
//check if the user from the skill contacted is the same of the user loggedin
if (msg.destinyUserId === this.props.userData.UserId) {
this.getAllContacts(this.state.currentContact.id);
}
});
//update the contacts updated
this.socket.on("contact_updated", msg => {
const { UserId } = this.props.userData;
//check if the user that updated the contact is not the the user loggedin and it is client or provider
if (msg.originUserId !== UserId && (msg.providerId === UserId || msg.clientId === UserId)) {
this.getAllContacts(this.state.currentContact.id);
}
});
//when a contact was removed by the other user
this.socket.on("contact_removed", msg => {
const { UserId } = this.props.userData;
//check if the user that removed the contact is not the the user loggedin and it is client or provider
if (msg.originUserId !== UserId && (msg.providerId === UserId || msg.clientId === UserId)) {
if (this.state.currentContact.id) {
this.getAllContacts(this.state.currentContact.id);
if (this.state.currentContact.id === msg.contact.id) {
this.setState({currentContact: {}})
}
}
}
});
//update chat if a message was received
this.socket.on("chat_msg_received", msg => {
let contacts = [...this.state.contacts];
if (contacts.length > 0) {
contacts.map(contact => {
if (contact.id === msg.contactId) {
contact.chat.push(msg.chat);
}
return contact;
});
}
if (this.mounted) {
this.setState({ contacts });
try {
this.refChatScreen.current.scrollTop = this.refChatScreen.current.scrollHeight;
} catch {} //on error do nothing
}
});
}
//guarantees the setState won't be called after component unmounts
componentWillUnmount = () => this.mounted = false;
componentDidMount = () => {
this.mounted = true;
this.pageType = this.props.match.params.pagetype; //client or request
const contactId = this.props.match.params.id; //contactId
if (this.pageType !== "client" && this.pageType !== "request") {
this.props.history.push('/');
}
this.getAllContacts(contactId);
}
setCurrentContact = data => {
let currentContact = {};
if (data) {
currentContact = {
id: data.id,
SkillId: data.SkillId,
skillName: data.Skill.name,
price: `${data.price} per ${Utils.getPriceTypeName(data.priceType)}`,
dealClosed: data.dealClosed,
dealStatus: data.dealStatus,
dealDate: data.dealDate,
note: data.note,
active: data.active,
createdAt: data.createdAt,
chat: data.chat,
agreedDate: data.agreedDate,
providerId: data.Skill.UserId,
clientId: data.UserId
};
if (this.props.match.params.pagetype === "client") {
currentContact.userOriginId = data.Skill.UserId;
currentContact.userDestinyId = data.UserId;
currentContact.userName = `${data.Skill.User.firstName} ${data.Skill.User.lastName}`;
currentContact.contactName = `${data.User.firstName} ${data.User.lastName}`;
}
else {
currentContact.userOriginId = data.UserId;
currentContact.userDestinyId = data.Skill.UserId;
currentContact.userName = `${data.User.firstName} ${data.User.lastName}`;
currentContact.contactName = `${data.Skill.User.firstName} ${data.Skill.User.lastName}`;
}
}
if (this.mounted) {
this.setState({ currentContact });
}
}
getAllContacts = contactId => {
const handleResult = res => {
if (this.mounted) {
let data = res.data.map(item => {
try { item.chat = item.chat ? JSON.parse(item.chat) : [];}
catch { item.chat = []; }
return item;
});
this.setState({ contacts: data });
if (res.data.length > 0 && contactId) {
//set the default opened chat
this.selectContact(contactId);
}
else {
this.setState({ currentContact: {} });
}
}
}
if (this.pageType === "client") {
//get all clients from the user loggedin
API.getUserClients().then(res => handleResult(res)).catch(err => console.log(err));
}
else {
//get all requests from the user loggedin
API.getUserRequests().then(res => handleResult(res)).catch(err => console.log(err));
}
}
selectContact = id => {
let currentContact = this.state.contacts.find(contact => contact.id.toString() === id.toString());
this.setCurrentContact(currentContact);
}
handleSelectContact = event => {
event.preventDefault();
if (event.target.name) {
this.selectContact(parseInt(event.target.name));
}
}
handleInputChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value });
}
submitMessage = event => {
event.preventDefault();
if (this.state.text.trim() !== "") {
this.setState({ loading: true });
let chatShot = [...this.state.currentContact.chat];
const contactId = this.state.currentContact.id;
const { userOriginId, userDestinyId } = this.state.currentContact;
let chat = {};
chat.text = this.state.text;
chat.user = this.state.currentContact.userName;
chat.dateTime = Moment().format('YYYYMMDDHHMMSS');
chatShot.push(chat);
this.setState({ text: "" });
const socket = io();
socket.emit("chat_msg_sent", { chat, contactId, userOriginId, userDestinyId });
API.updateContact({ id: contactId, chat: JSON.stringify(chatShot) })
.then(() => {
this.setState({ loading: false });
this.refChatText.current.focus();
})
.catch(err => console.log("update error", err.response));
}
}
chatLoaded = () => {
this.refChatScreen.current.scrollTop = this.refChatScreen.current.scrollHeight;
}
makeDeal = id => {
this.setState({ loadingDetails: true });
let data = {
id: id,
dealStatus: "P",
note: this.state.note,
dealDate: Moment().format('YYYY-MM-DD'),
agreedDate: this.state.currentContact.agreedDate
};
this.updateContactDetails(data);
}
answerDeal = (answer, id) => {
this.setState({ loadingDetails: true });
let data = {
id: id,
dealStatus: answer ? "C" : "D",
note: this.state.currentContact.note,
agreedDate: answer ? Moment().format('YYYY-MM-DD') : null,
dealDate: this.state.currentContact.dealDate
};
this.updateContactDetails(data);
}
updateContactDetails = data => {
API.updateContact(data).then(() => {
let contacts = this.state.contacts;
let currentContact = this.state.currentContact;
contacts.map(contact => {
if (contact.id === data.id) {
contact.dealStatus = data.dealStatus;
contact.note = data.note;
contact.dealDate = data.dealDate;
contact.agreedDate = data.agreedDate;
}
return contact;
});
currentContact.dealStatus = data.dealStatus;
currentContact.note = data.note;
currentContact.dealDate = data.dealDate;
currentContact.dateClosed = data.dateClosed;
currentContact.agreedDate = data.agreedDate;
//send info to other user
const socket = io();
socket.emit("update_contact", {
contact: data,
originUserId: this.props.userData.UserId,
providerId: currentContact.providerId,
clientId: currentContact.clientId
});
//update state contact info
if (this.mounted) {
this.setState({ currentContact, contacts, loadingDetails: false });
}
})
.catch(err => {
console.log("making a deal error", err.response);
this.setState({ loadingDetails: false });
});
}
removeContact = id => {
this.setState({ loadingDetails: true });
let data = {
id: id,
active: false
};
API.updateContact(data).then(() => {
let contacts = [...this.state.contacts];
let currentContact = this.state.currentContact;
contacts = contacts.filter(contact => contact.id.toString() !== id.toString());
//send info to client
const socket = io();
socket.emit("remove_contact", {
contact: data,
originUserId: this.props.userData.UserId,
providerId: this.state.currentContact.providerId,
clientId: this.state.currentContact.clientId
});
if (contacts.length === 0) {
currentContact = {};
}
else {
//update current contact and contacts
if (currentContact.id) {
if (id.toString() === this.state.currentContact.id.toString()) {
currentContact = {};
}
}
}
//update state contact info
this.setState({ contacts, currentContact, loadingDetails:false });
})
.catch(err => {
console.log("removing contact error", err.response);
this.setState({ loadingDetails: false });
});
}
render() {
return (
<PageContainer title={this.pageType === "client"?"Your Clients":"Your Requests"}>
<Row>
<Col md="4">
<ListGroup defaultActiveKey={`#link${this.state.currentContact.id}`}>
{this.state.contacts.map(contact => {
return (
<ListGroup.Item key={contact.id} action active={this.state.currentContact.id === contact.id} href={`#link${contact.id}`} name={contact.id} title="Personal Info" onClick={this.handleSelectContact}>
{this.pageType === "client" ?
<>
<b>{`${contact.User.firstName} ${contact.User.lastName}`}</b><br />
<i>{contact.Skill.name}</i>
</>
:
<>
<b>{contact.Skill.name}</b><br />
{`${contact.Skill.User.firstName} ${contact.Skill.User.lastName}`}
</>
}
</ListGroup.Item>
);
})}
</ListGroup>
</Col>
<Col md="8">
{this.state.currentContact.id ?
<>
<Chat
text={this.state.text}
loading={this.state.loading}
submitMessage={this.submitMessage}
handleInputChange={this.handleInputChange}
contact={this.state.currentContact}
refChatScreen={this.refChatScreen}
refChatText={this.refChatText}
chatLoaded={this.chatLoaded}
/>
<ContactDetail
contact={this.state.currentContact}
{...this.props}
note={this.state.note}
handleInputChange={this.handleInputChange}
makeDeal={this.makeDeal}
removeContact={this.removeContact}
answerDeal={this.answerDeal}
loading={this.state.loadingDetails}
/>
</>
:null}
</Col>
</Row>
</PageContainer>
);
}
}
export default Contact;
|
65ad0156f1882bb8f53c70cc13cb077b7c3fc5a1
|
[
"Markdown",
"SQL",
"JavaScript"
] | 33 |
Markdown
|
carolinapc/skillshub
|
9fd9b077041dbe81187904e2c1ed4376527fde93
|
a7fcc40623cab4b0d91af57f7ab073ed81dc3e44
|
refs/heads/master
|
<repo_name>quangtrm/JX3PC<file_sep>/JX3Helper/JX3Helper.lua
JX3Helper = {
bOn = true,
bAutoRotation = false,
nFrame = 0,
bGrindBot = false,
bHealAutoSelect = false,
gReturnCheckPoint = {
gnX = 0,
gnY = 0,
gnZ = 0,
},
szLastKungfu = "",
szHealSeclectOption = {
bPartyOnly = true;
bWorld = false;
},
}
function JX3Helper.OnFrameBreathe()
Core.UpdateVars()
--print("loop")
--Core.Cast("Vũ Lâm Linh", true)
if JX3Helper.nFrame > GetLogicFrameCount() then
return
end
--print("loop")
if JX3Helper.bAutoRotation then
if force == "Minh Giáo" then
Rotation.MinhGiao()
elseif force == "Thất Tú" then
Rotation.ThatTu()
elseif force == "Đường Môn" then
Rotation.DuongMon()
elseif force == "Ngũ Độc" then
Rotation.NguDoc()
elseif force == "Thiếu Lâm" then
Rotation.ThieuLam()
elseif force == "Thiên Sách" then
Rotation.ThienSach()
elseif force == "Vạn Hoa" then
Rotation.VanHoa()
elseif force == "Thuần Dương" then
Rotation.ThuanDuong()
elseif force == "Tàng Kiếm" then
Rotation.TangKiem()
end
if Core.GetCurrentKungfu() ~= JX3Helper.szLastKungfu then
Core.print("Kungfu changed to " .. Core.GetCurrentKungfu())
JX3Helper.szLastKungfu = Core.GetCurrentKungfu()
end
end
if JX3Helper.bGrindBot then
needtarget()
end
JX3Helper.nFrame = GetLogicFrameCount()+1
end
JX3Helper.GetMenuList = function()
local submenu={
szOption = "JX3Helper",
{
szOption = "Auto Rotation",
bCheck = true,
bChecked = JX3Helper.bAutoRotation,
fnAction = function(UserData, bCheck)
JX3Helper.bAutoRotation = not JX3Helper.bAutoRotation
end
},
{
szOption = "Heal Bot",
{
szOption = "Start",
bCheck = true,
bChecked = JX3Helper.bHealAutoSelect,
fnAction = function(UserData, bCheck)
JX3Helper.bHealAutoSelect = not JX3Helper.bHealAutoSelect
end
},
{
szOption = "Options",
{
szOption = "Party Only",
bCheck = true,
bChecked = JX3Helper.szHealSeclectOption.bPartyOnly,
fnAction = function(UserData, bCheck)
JX3Helper.szHealSeclectOption.bPartyOnly = not JX3Helper.szHealSeclectOption.bPartyOnly
end
},
{
szOption = "World",
bCheck = true,
bChecked = JX3Helper.szHealSeclectOption.bWorld,
fnAction = function(UserData, bCheck)
JX3Helper.szHealSeclectOption.bWorld = not JX3Helper.szHealSeclectOption.bWorld
end
},
},
},
{
szOption = "Grind Bot",
bCheck = true,
bChecked = JX3Helper.bGrindBot,
fnAction = function(UserData, bCheck)
JX3Helper.bGrindBot = not JX3Helper.bGrindBot
end
},
}
return submenu
end
RegisterEvent("LOGIN_GAME", function()
local tMenu = {
function()
return {JX3Helper.GetMenuList()}
end,
}
Player_AppendAddonMenu(tMenu)
end)
JX3Helper.nFrame = GetLogicFrameCount()+1
Wnd.OpenWindow("interface/JX3Helper/JX3Helper.ini", "JX3Helper")<file_sep>/JX3Helper/Rotation.lua
Rotation = {}
function Rotation.Check()
Core.print("Ngon rồi")
end
function Rotation.MinhGiao()
if not etarget then return end
--if not combat then return end
Core.Cast("Xuống Ngựa", onhorse)
if kungfu == "<NAME> Lưu Ly Thể" then
Core.Cast("Ảo Quang Bộ", tdistance >= 10 and tdistance <= 20)
Core.Cast("Lực Độ Ách", life < 50)
Core.Cast("Tính Mệnh Hải", life < 40)
Core.Cast("Đốc Mạch-Bách Hội", life < 40)
Core.Cast("Quang Minh Tướng", (moon or sun) and (tplayer or tboss))
Core.Cast("Thánh Minh Hựu", life < 60 and (moon or sun))
Core.Cast("Triều Thánh Ngôn", life < 30)
Core.Cast("Xung Mạch-Quan Môn", (moon or sun) and (tplayer or tboss))
Core.Cast("Sinh Tử Kiếp", sun and tplayer)
Core.Cast("Tịnh Thế Phá Ma Kích", moon or sun)
Core.Cast("Hoàng Nhật Chiếu", nobuff("Chiết Xung") and tdistance <= 4)
Core.Cast("Hàn Nguyệt Diệu", nobuff("Chiết Xung") and tdistance <= 4)
Core.Cast("Giới Hỏa Trảm", tnobuff("Giới Hỏa"))
Core.Cast("Quy Tịch Đạo", true)
Core.Cast("Liệt Nhật Trảm", tnobuff("Tịch Dương"))
Core.Cast("Ngân Nguyệt Trảm", tnobuff("Ngân Nguyệt Trảm"))
Core.Cast("Xích Nhật Luân", renemies >= 2)
Core.Cast("U Nguyệt Luân", renemies <= 1)
end
if kungfu == "Phần Ảnh Thánh Quyết" then
--print("fighting")
Core.Cast("Sinh Diệt Dư Đoạt", tplayer or tboss)
Core.Cast("Ám Trần Di Tán", nobuff("Ám Trần Di Tán") and nocombat)
Core.Cast("Lưu Quang Tù Ảnh", tdistance >= 8)
Core.Cast("Khu Dạ Đoạn Sầu", buff("Ám Trần Di Tán"))
Core.Cast("Xung Mạch-Quang Môn", (moon or sun) and (tplayer or tboss))
Core.Cast("Quang Minh Tướng", (moon or sun) and (tplayer or tboss))
Core.Cast("Thánh Minh Hựu", life < 60 and sun)
Core.Cast("Tịnh Thế Phá Ma Kích", moon or sun)
Core.Cast("Sinh Tử Kiếp", sun and tplayer)
Core.Cast("Xung Mạch-U Môn", nocd("Quang Minh Tướng"))
Core.Cast("Nghiệp Hải Tội Phọc", tplayer)
Core.Cast("Bố Úy Ám Hình", tlife < 80)
Core.Cast("Liệt Nhật Trảm", tnobuff("Tịch Dương"))
Core.Cast("Ngân Nguyệt Trảm", tnobuff("Ngân Nguyệt Trảm"))
Core.Cast("Hoàng Nhật Chiếu", menemies >= 3)
Core.Cast("Hàn Nguyệt Diệu", menemies >= 3)
Core.Cast("Xích Nhật Luân", menemies >= 2)
Core.Cast("U Nguyệt Luân", menemies < 2)
end
end
function Rotation.ThatTu()
Core.Cast("Bà La Môn", nobuff("Tụ Khí"))
Core.Cast("Danh Động Tứ Phương", nobuff("Kiếm Vũ") and stay)
if kungfu == "<NAME>" then
if nocombat then return end
if not etarget then return end
Core.Cast("Phồn Âm Cấp Tiết", tplayer or tboss)
Core.Cast("Kiếm Thần Vô Ngã", tdistance <= 10 and nobuff("Kiếm Thần Vô Ngã"))
Core.Cast("Kiếm Khí Trường Giang", dance >= 3)
Core.Cast("Kiếm Phá Hư Không", dance == 10 and renemies >= 3)
Core.Cast("Danh Kiếm Vô Địch", dance <= 8)
Core.Cast("Kiếm Linh Hoàn Vũ", renemies >= 3)
Core.Cast("Mãn Đường Thế", dance <= 5 and tboss)
Core.Cast("Long Trì Nhạc", tboss)
Core.Cast("Đại Huyền Cấp Khúc", true)
Core.Cast("Thiên Địa Đê Ngang", life < 65)
Core.Cast("Thước Đạp Chi", life < 30)
end
if kungfu == "<NAME> <NAME>" then
IgnoreChannelling = {"Phong <NAME> Ngang", "<NAME> <NAME>", "Linh Lung <NAME>u", "Khiêu Châu Hám Ngọc"}
Core.Cast("Long Trì Nhạc", mana < 80)
if JX3Helper.bHealAutoSelect then
Core.HealAutoSelect()
end
if not tplayer then return end
if etarget then return end
Core.Heal("Tả Hoàn Hữu Chuyển", needaoeheal)
Core.Heal("Khiêu Châu Hám Ngọc", dispelabledebuff)
Core.Heal("Vũ Lâm Linh", nobuff("Vũ Lâm Linh") and tlife < 40)
Core.Heal("Phong Tụ Đê Ngang", tlife <= 30)
Core.Heal("Linh Lung Không Hầu", tlife <= 30 and cd("Phong Tụ Đê Ngang"))
Core.Heal("Vương Mẫu Huy Duệ", tlife <= 50)
Core.Heal("Tường Loan Vũ Liễu", tlife <= 90 and tnobuff("Bay Lượn"))
Core.Heal("Thượng Nguyên Điểm Hoàn", tlife <= 85 and tnobuff("Thượng Nguyên Điểm Hoàn"))
Core.Heal("Hồi Tuyết Phiêu Dao", tlife <= 80)
Core.Cast("Thiên Địa Đê Ngang", life <= 65)
Core.Cast("Thước Đạp Chi", life <= 30)
end
end
function Rotation.DuongMon()
if kungfu == "Kinh Vũ Quyết" then
Core.print("Chưa code")
end
if kungfu == "Thiên La Ngụy Đạo" then
Core.print("Chưa code")
end
end
function Rotation.NguDoc()
if kungfu == "Bổ Thiên Quyết" then
Core.print("Chưa code")
end
if kungfu == "Độc Kinh" then
Core.print("Chưa code")
end
end
function Rotation.ThieuLam()
if kungfu == "Dịch Cân Kinh" then
Core.print("Chưa code")
end
if kungfu == "Tẩy Tủy Kinh" then
Core.print("Chưa code")
end
end
function Rotation.ThienSach()
if kungfu == "Thiết Lao Luật" then
Core.print("Chưa code")
end
if kungfu == "Ngạo Huyết Chiến Ý" then
Core.print("Chưa code")
end
end
function Rotation.VanHoa()
if kungfu == "Hoa Gian Du" then
Core.print("Chưa code")
end
if kungfu == "Ly Kinh Dịch Đạo" then
Core.print("Chưa code")
end
end
function Rotation.ThuanDuong()
if kungfu == "Thái Hư Kiếm Ý" then
Core.print("Chưa code")
end
if kungfu == "Tử Hà Công" then
Core.print("Chưa code")
end
end
function Rotation.TangKiem()
if kungfu == "Vấn Thủy Quyết" then
Core.print("Chưa code")
end
if kungfu == "Sơn Cư Kiếm Ý" then
Core.print("Chưa code")
end
end
<file_sep>/JX3Dumper/Inject/Inject.cpp
#include <windows.h>
#include <stdio.h>
PROCESS_INFORMATION processInfo;
int Inject(HANDLE hProcess, char *fileName)
{
HANDLE hThread;
char filePath [_MAX_PATH];
void* pLibRemote = 0;
DWORD hLibModule = 0;
HMODULE hKernel32 = ::GetModuleHandle("Kernel32");
if (::GetCurrentDirectoryA(_MAX_PATH, filePath) == 0)
return false;
::strcat_s(filePath, _MAX_PATH, fileName);
pLibRemote = ::VirtualAllocEx( hProcess, NULL, sizeof(filePath), MEM_COMMIT, PAGE_READWRITE );
if( pLibRemote == NULL )
return false;
::WriteProcessMemory(hProcess, pLibRemote, (void*)filePath,sizeof(filePath),NULL);
hThread = ::CreateRemoteThread( hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE) ::GetProcAddress(hKernel32,"LoadLibraryA"),
pLibRemote, 0, NULL );
if( hThread == NULL )
goto JUMP;
::WaitForSingleObject( hThread, INFINITE );
::GetExitCodeThread( hThread, &hLibModule );
::CloseHandle( hThread );
JUMP:
::VirtualFreeEx( hProcess, pLibRemote, sizeof(filePath), MEM_RELEASE );
if( hLibModule == NULL )
return false;
return 0;
}
int StartGame()
{
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(STARTUPINFO));
char *params = "jx3client.exe DOTNOTSTARTGAMEBYJX3CLIENT.EXE";
BOOL cp = CreateProcess(NULL,params,NULL,NULL,TRUE,CREATE_SUSPENDED,NULL,NULL,&startupInfo, &processInfo);
if(cp)
{
printf("Game started, PID %d\n", processInfo.dwProcessId);
Sleep(200);
printf("Injecting dll ...\n");
Inject(processInfo.hProcess, "\\JX3Hook.dll");
Sleep(500);
ResumeThread(processInfo.hThread);
printf("Check JX3Root/output for extracted files\n");
getchar();
return 0;
}
return 0;
}
int main(int argc,char **argv)
{
//SetCurrentDirectory("D:\Games\VoLamTruyenKyPhienBan3D\data");
printf("JX3 NewPack content dumper - KhaNP\n");
printf("Starting game client ...\n");
StartGame();
return 0;
}<file_sep>/JX3Helper/Core.lua
Core = {}
--Global func
IgnoreChannelling = {}
buff = function(buffName, t) return Core.IsActiveBuff(buffName, me) end
nobuff = function(buffName, t) return not Core.IsActiveBuff(buffName, me) end
cd = function(skillName) return not Core.CheckCDs(skillName) end
nocd = function(skillName) return Core.CheckCDs(skillName) end
tbuff = function(buffName, t) return Core.IsActiveBuff(buffName, target) end
tnobuff = function(buffName, t) return not Core.IsActiveBuff(buffName, target) end
needtarget = function() Core.FindTarget() end
needaoeheal = false
bignorecast = true
function Core.UpdateVars()
me = GetClientPlayer()
if me then
bignorecast = false
--Core.print(bignorecast)
target = GetTargetHandle(me.GetTarget())
dance = me.nAccumulateValue
life = math.floor(me.nCurrentLife * 100 / me.nMaxLife)
mana = math.floor(me.nCurrentMana * 100 / me.nMaxMana)
rage = math.floor(me.nCurrentRage * 100 / me.nMaxRage)
sun = me.nSunPowerValue == 1
moon = me.nMoonPowerValue == 1
combat = me.bFightState
nocombat = not me.bFightState
channelling = me.GetOTActionState() == 2
onhorse = me.bOnHorse
kungfu = Core.GetCurrentKungfu()
force = Core.GetCurrentForce()
dispelabledebuff = Core.HaveDispelableDebuff(me)
menemies = Core.GetEnemy(400, 360)
renemies = Core.FindEnemiesNearTarget()
stay = me.nMoveState == 1 or me.nMoveState == 7
if target then
tlife = math.floor(target.nCurrentLife * 100 / target.nMaxLife)
tmana = math.floor(target.nCurrentMana * 100 / target.nMaxMana)
etarget = IsEnemy(me.dwID, target.dwID)
tdistance = Core.Distance(me, target)
tplayer = IsPlayer(target.dwID)
tboss = target.nLevel >= 82
dispelabledebuff = Core.HaveDispelableDebuff(target)
else
target = 0
tdistance = 0
tplayer = false
etarget = false
tlife = 0
tmana = 0
tboss = false
end
end
end
function Core.print(...)
local a = {...}
for i, v in ipairs(a) do
a[i] = tostring(v)
end
OutputMessage("MSG_SYS", "[JX3Helper] " .. table.concat(a, "\t").. "\n" )
end
function Core.max(t, fn)
if #t == 0 then return nil, nil end
local key, value = 1, t[1]
for i = 2, #t do
if fn(value, t[i]) then
key, value = i, t[i]
end
end
return key, value
end
function Core.GetEnemy(nRadius, nAngle)
local CharacterIDArray, count = GetClientPlayer().SearchForEnemy(nRadius, nAngle)
return count
end
function Core.FindEnemiesNearTarget()
local p = GetClientPlayer()
local t = GetTargetHandle(p.GetTarget())
local count = 0
if not t then return count end
local eIDs, ecount = p.SearchForEnemy(1280, 90)
if ecount == 0 then return count end
for _, v in pairs(eIDs) do
if v ~= t.dwID then
if IsPlayer(v) then
local tt = GetPlayer(v)
else
local tt = GetNpc(v)
end
if not tt then return count end
if Core.Distance(t, tt) <= 8 then
count = count + 1
end
end
end
return count
end
function Core.HealAutoSelect()
local partyLife = {}
local charIDs, count = GetClientPlayer().SearchForAllies(1280, 360)
local p = GetClientPlayer()
if count == 0 then return end
partyLife[p.dwID] = math.floor(p.nCurrentLife * 100 / p.nMaxLife)
for _, v in pairs(charIDs) do
if IsPlayer(v) then
if JX3Helper.szHealSeclectOption.bPartyOnly then
if p.IsPlayerInMyParty(v) then
local t = GetPlayer(v)
partyLife[v] = math.floor(t.nCurrentLife * 100 / t.nMaxLife)
end
end
if JX3Helper.szHealSeclectOption.bWorld then
local t = GetPlayer(v)
partyLife[v] = math.floor(t.nCurrentLife * 100 / t.nMaxLife)
end
end
end
local pt = {}
local count = 0
for _, v in pairs(partyLife) do
if v <= 95 then
table.insert(pt, v)
end
if v <= 70 then
count = count + 1
end
end
if next(pt) == nil then return end
if count >= 4 then
needaoeheal = true
return
end
needaoeheal = false
table.sort(pt)
for x,v in pairs(partyLife) do
if v == pt[1] then
SetTarget(TARGET.PLAYER, x)
end
end
end
function Core.Distance(p, t)
if not t or not p then
return false
end
local nX1 = p.nX
local nX2 = t.nX
local nY1 = p.nY
local nY2 = t.nY
local strdis = tostring((((nX1 - nX2) ^ 2 + (nY1 - nY2) ^ 2) ^ 0.5)/64)
return tonumber(string.format("%.1f",strdis))
end
function Core.CheckCDs(skillName)
local p = GetClientPlayer()
local skillID = g_SkillNameToID[skillName]
bOnCD,currentCDTime,totalCDTime = p.GetSkillCDProgress(skillID,p.GetSkillLevel(skillID))
return currentCDTime/16 == 0
end
function Core.IsActiveBuff(buffName, t)
if not t then return false end
local buffList = t.GetBuffList()
if buffList then
for z,x in ipairs(buffList) do
local name = Table_GetBuffName(x.dwID, x.nLevel)
if buffName == name then
return true
end
end
end
return false
end
function Core.HaveDispelableDebuff(t)
if not t then return end
local buffList = t.GetBuffList()
if buffList then
for z,x in ipairs(buffList) do
if IsBuffDispel(x.dwID, x.nLevel) then
return true
end
end
end
return false
end
function Core.Cast(skillName, condition)
if condition and not bignorecast then
local skillID = g_SkillNameToID[skillName]
if(Core.CheckCDs(skillName)) then
if not channelling then
OnAddOnUseSkill(skillID)
bignorecast = true
end
end
end
end
function Core.Heal(skillName, condition)
local skillID = g_SkillNameToID[skillName]
if tlife == 0 then return end
if condition and not bignorecast then
if(Core.CheckCDs(skillName)) then
if next(IgnoreChannelling) ~= nil then
for _, v in pairs(IgnoreChannelling) do
if v == skillName then
OnAddOnUseSkill(skillID)
bignorecast = true
return
end
end
end
if not channelling then
OnAddOnUseSkill(skillID)
bignorecast = true
end
end
end
end
function Core.FaceToTarget()
local player = GetClientPlayer()
local target = GetTargetHandle(player.GetTarget())
if not target then
return
end
local RelX=target.nX-player.nX
local RelY=target.nY-player.nY
local CosPhy=RelX/((RelX^2+RelY^2)^0.5)
local Phy
if RelY<0 then
Phy=6.28-math.acos(CosPhy)--
else
Phy=math.acos(CosPhy)
end
TurnTo(Phy*256/6.28)
end
function Core.FindTarget()
if JX3Helper.bGrindBot then
local p = GetClientPlayer()
local t = GetTargetHandle(p.GetTarget())
local lifePercent = p.nCurrentLife * 100 / p.nMaxLife
local dwTargetType, dwTargetID = p.GetTarget()
if dwTargetID == 0 then
if lifePercent < 100 and not p.bFightState then
if Core.IsActiveBuff(103, p) then return end
OnAddOnUseSkill(17)
return
end
local _, count = Core.GetAllMeleeEnemy()
if count == 0 then
SearchEnemy()
t = GetTargetHandle(p.GetTarget())
Core.FaceToTarget()
if dwTargetID == 0 then
Core.ReturnCheckPoint()
end
end
end
--if t.nLevel < 70 then dwTargetID = 0 return end
--if Core.Distance(p, t) > 40 then dwTargetID = 0 return end
dwTargetType, dwTargetID = p.GetTarget()
if IsEnemy(p.dwID, dwTargetID) then
AutoMoveToTarget(dwTargetType, dwTargetID)
Core.FaceToTarget()
end
end
end
function Core.IsChannelling()
return GetClientPlayer().GetOTActionState() == 2
end
function Core.ReturnCheckPoint()
local p = GetClientPlayer()
if p.nMoveState ~= 3 then
AutoMoveToPoint(JX3Helper.gReturnCheckPoint.gnX, JX3Helper.gReturnCheckPoint.gnY, JX3Helper.gReturnCheckPoint.gnZ)
end
end
function Core.GetCurrentKungfu()
local p = GetClientPlayer()
local k = p.GetKungfuMount()
return Table_GetSkillName(k.dwSkillID)
end
function Core.GetCurrentForce()
local p = GetClientPlayer()
return GetForceTitle(p.dwForceID)
end<file_sep>/JX3Helper/info.ini
[JX3Helper]
name=JX3Helper
desc=JX3Helper - ISO Team
version=0.8
default=1
lua_0=interface\JX3Helper\JX3Helper.lua
lua_1=interface\JX3Helper\Rotation.lua
lua_2=interface\JX3Helper\Core.lua<file_sep>/JX3Helper/JX3Helper.ini
[JX3Helper]
._WndType=WndFrame
._Parent=Normal
ScriptFile=Interface\JX3Helper\JX3Helper.lua
BreatheWhenHide=1
<file_sep>/README.md
# JX3PC
Dăm ba cái code linh tinh từ LUA tới C/C++ cho Võ Lâm Truyền Kỳ 3 PC
<file_sep>/JX3Dumper/hook/hook.cpp
#include <windows.h>
#include <stdio.h>
#include <direct.h>
#include "detours.h"
#define SIZE 6
//#define savelua
#define codeinject
#define codehijack
typedef UINT(__cdecl *PLUALOADBUFFER)(int, char*, int, char*);
UINT __cdecl h_luaL_loadbuffer(int, char*, int, char*);
PLUALOADBUFFER o_luaL_loadbuffer = NULL;
int CreateFolder(char * nPath)
{
char tPath[255];
if (nPath[0]=='/'||nPath[0]=='\\')
{
nPath++;
}
for (size_t i = 1; i < strlen(nPath); i++)
{
if (nPath[i] == '/')nPath[i] = '\\';
if (nPath[i] == '\\')
{
memcpy(tPath, nPath, i );
tPath[i] = 0;
_mkdir(tPath);
}
}
return 1;
}
INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
switch(Reason)
{
case DLL_PROCESS_ATTACH:
{
while (!o_luaL_loadbuffer)
{
o_luaL_loadbuffer = (PLUALOADBUFFER) GetProcAddress(GetModuleHandle("engine_lua5.dll"), "luaL_loadbuffer");
}
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&) o_luaL_loadbuffer, h_luaL_loadbuffer);
DetourTransactionCommit();
break;
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
UINT __cdecl h_luaL_loadbuffer(int lState, char *lBuffer, int lSize, char *lFileName)
{
#ifdef savelua
FILE *fp;
char tmp[256];
sprintf_s(tmp, sizeof(tmp), "outlua\\%s", lFileName);
CreateFolder(tmp);
fopen_s(&fp, tmp, "wb");
fwrite(lBuffer, 1, lSize, fp);
fclose(fp);
#endif
char *filterName;
if (strstr(lFileName, "interface") != NULL || strstr(lFileName, "Interface") != NULL )
{
return o_luaL_loadbuffer(lState, lBuffer, lSize, lFileName);
}
if (lFileName[0] == '@')
{
filterName = lFileName + 1;
if (filterName[0] == '\\')
filterName = filterName + 1;
}
if (filterName[0] == '\\')
filterName = filterName + 1;
//OutputDebugString(filterName);
FILE *fp;
if (fopen_s(&fp, filterName, "r"))
{
//OutputDebugString("Cant open file.");
return o_luaL_loadbuffer(lState, lBuffer, lSize, lFileName);
}
else
{
OutputDebugString("Injected");
OutputDebugString(filterName);
fseek(fp, 0, SEEK_END);
int fileSize = ftell(fp);
rewind(fp);
char *newbuff = (char*) malloc(fileSize + 1);
memset(newbuff, 0, fileSize + 1);
fread(newbuff, 1, fileSize, fp);
fclose(fp);
return o_luaL_loadbuffer(lState, newbuff, strlen(newbuff), lFileName);
}
return o_luaL_loadbuffer(lState, lBuffer, lSize, lFileName);
}
|
d7213dc4ec563874a29da775fa1b1a5d5bdd27b0
|
[
"Markdown",
"C++",
"INI",
"Lua"
] | 8 |
Markdown
|
quangtrm/JX3PC
|
9a1b8104cf1dc17076dd9ad1852f1a9c5b36d641
|
e0bea2d5615c38c019f8e6d971015462815e3629
|
refs/heads/master
|
<file_sep>package pl.sda.library.view;
import pl.sda.library.table.model.CrudDataTableModel;
import pl.sda.library.table.model.JdbcDataTableModel;
public class JdbcAppView extends AppView {
@Override
protected CrudDataTableModel getDataTableModel() {
return new JdbcDataTableModel();
}
}
<file_sep>package pl.sda.library.table.model;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ConcurrentModificationException;
import java.util.LinkedList;
import java.util.List;
import java.util.SimpleTimeZone;
import pl.sda.library.model.Book;
public class JdbcDataTableModel extends CrudDataTableModel {
private static final long serialVersionUID = 1L;
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost/sda?useSSL=false";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "";
public JdbcDataTableModel() {
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
filterByName("");
}
@Override
public int getRowCount() {
//liczba książek
BigDecimal bigDecimal = null;
try {
Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select count(*) from book");
if (result.next()) {
bigDecimal = result.getBigDecimal(1);
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return bigDecimal.intValue();
}
@Override
public int getColumnCount() {
return 5;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Book book = getByName(filter).get(rowIndex);
switch (columnIndex) {
case 0:
return book.getId();
case 1:
return book.getTitle();
case 2:
return book.getAuthorFirstName();
case 3:
return book.getAuthorLastName();
case 4:
return book.getCategories();
default:
return null;
}
}
@Override
public Book getById(int id) {
//książka na podstawie id
Book bookToReturn = new Book();
Connection connection = null;
try {
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
PreparedStatement statement = connection.prepareStatement("SELECT b.title AS title, b.id AS id," +
" a.first_name AS firstName, a.last_name AS lastName" +
" FROM book AS b JOIN author AS a ON b.author_id = a.id " +
"WHERE b.id = ?");
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
bookToReturn.setId(resultSet.getInt("id"));
bookToReturn.setTitle(resultSet.getString("title"));
bookToReturn.setAuthorFirstName(resultSet.getString("firstName"));
bookToReturn.setAuthorLastName(resultSet.getString("lastName"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return bookToReturn;
}
@Override
public List<Book> getByName(String name) {
//książki na podstawie nazwy
List<Book> listOfBook = new LinkedList<>();
//klasa Conncection sluzy do polaczenia z baza danych
//aby moc zamknac w Finally nalezy Connection zainicjalizowac tutaj
Connection connection = null;
try {
// driverManager umozliwa laczenie sie z abaza danych, gdzie podajemy dane do polaczenia
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
//majac polaczenia mozna wykonac metode createStatement ktora umozliwia wyslanie zapytania do SQL
Statement statement = connection.createStatement();
//tylko executeQuery umozliwa wykonania SELECTa
ResultSet executeQuery = statement.executeQuery("SELECT b.title AS title, b.id AS id," +
" a.first_name AS firstName, a.last_name AS lastName" +
" FROM book AS b JOIN author AS a ON b.author_id = a.id");
//aby otrzymywac wyniki nalezy iterowac po "bazie" i gdy executeQuery.next ma nexta to bedziemy otrzymywac koleje tytuly
while (executeQuery.next()) {
Book book = new Book();
book.setTitle(executeQuery.getString("title"));
book.setId(executeQuery.getInt("id"));
book.setAuthorFirstName(executeQuery.getString("firstName"));
book.setAuthorLastName(executeQuery.getString("lastName"));
listOfBook.add(book);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return listOfBook;
}
@Override
public void create(Book book) {
//dodanie książki
Connection connection = null;
try {
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
connection.setAutoCommit(false);
PreparedStatement statement = connection.prepareStatement("INSERT INTO author (first_name, last_name) " +
"VALUES (?,?)", Statement.RETURN_GENERATED_KEYS); //znaki zapytania wskazuja nam to co insertujemy, STALA RETURN zwraca nam id dodanego authora
statement.setString(1, book.getAuthorFirstName());
statement.setString(2, book.getAuthorLastName());
statement.executeUpdate(); //wysylamy do bazy danych nasz INSERT
ResultSet generatedKeys = statement.getGeneratedKeys();
int authorId = 0;
if (generatedKeys.next()) {
authorId = generatedKeys.getInt(1);
}
statement.close();
statement = connection.prepareStatement("INSERT INTO book (title, author_id) " +
"VALUES (?, ?)");
statement.setString(1, book.getTitle());
statement.setInt(2, authorId);
statement.executeUpdate();
statement.close();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
refresh();
}
@Override
public void update(Book book) {
//modyfikacja książki zrobic do domu
Connection connection = null;
try {
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
connection.setAutoCommit(false); //dodanie TRANSAKCJI ktora zablokuje update jest bedzie cos nie tak
PreparedStatement statement = connection.prepareStatement("UPDATE author a SET a.first_name = ?, " +
"a.last_name = ? WHERE a.id = (SELECT b.author_id FROM book b WHERE b.id = ?)");
statement.setString(1, book.getAuthorFirstName());
statement.setString(2, book.getAuthorLastName());
statement.setInt(3, book.getId());
statement.executeUpdate();
statement.close(); //moze byc ale nie musi
statement = connection.prepareStatement("UPDATE book SET title = ? WHERE id = ?");
statement.setString(1, book.getTitle());
statement.setInt(2, book.getId());
statement.executeUpdate();
connection.commit(); //wykonanie transakcji
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback(); //cofniecie transakcji gdyby poszedl blad
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
refresh();
}
@Override
public void delete(Book book) {
//usunięcie książki
Connection connection = null;
try {
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
connection.setAutoCommit(false);
PreparedStatement statement = connection.prepareStatement("DELETE FROM book_category WHERE book_id = ?");
statement.setInt(1, book.getId());
statement.executeUpdate();
statement = connection.prepareStatement("DELETE FROM book WHERE id = ?");
statement.setInt(1, book.getId());
statement.executeUpdate();
statement.close();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
refresh();
}
}
|
af0a6fc37ae105cc9833d130b336e9205dd059bf
|
[
"Java"
] | 2 |
Java
|
snafx/library-JDBC
|
a43c9b101128a9a75c20ab699034938e238d4eec
|
b0a02111599eb10b9235b5745e29d8b31b7edea3
|
refs/heads/main
|
<repo_name>JoyceeeeeLi/Avatar<file_sep>/src/Avatar.java
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class Avatar extends Application {
@Override
public void start(Stage stage) throws Exception{
// Parent root = FXMLLoader.load(getClass().getResource("avatar.fxml"));
// get controller
FXMLLoader loader = new FXMLLoader(getClass().getResource("avatar.fxml"));
Parent root= loader.load();
Controller c = loader.getController();
c.addSaveButton(stage);
c.handleResizeEvent(stage);
Scene scene = new Scene(root);
stage.setMinWidth(800);
stage.setMinHeight(400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args){
launch(args);
}
}<file_sep>/README.txt
<NAME>
20798712 q362li
openjdk 11.0.7 2020-04-14
MacOS 10.13.6 (MacBook Pro 2017)
* Used image files distributed in-class.
* No changes from specification.
* Extra feature I implemented:
* Background: users can change the backgound color or set it as transparent (5 marks).
* Please run the Avatar class
|
15e9eceaffb7245b4506906d67a77ca222dd3cf4
|
[
"Java",
"Text"
] | 2 |
Java
|
JoyceeeeeLi/Avatar
|
e1f69339723121b7e5f248dd573c6160aeef013f
|
4ecbb72fe39f7684ef13f2c08287ad231dd3af78
|
refs/heads/master
|
<file_sep>#ifndef __COLOR_PRINT_H__
#define __COLOR_PRINT_H__
#if defined __WIN32 || defined __WIN64 || defined WIN32 || defined WIN64
#ifndef WINDOWS
#define WINDOWS
#endif
// other platform
#endif
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef WINDOWS
#include <windows.h>
#else
#define TRUE true
#endif
#if defined(__cplusplus)
extern "C" {
#endif
/* Colors */
enum cp_color {
#ifdef WINDOWS
CP_FG_BLACK = 0x0000,
CP_FG_BLUE = 0x0001,
CP_FG_GREEN = 0x0002,
CP_FG_CYAN = 0x0003,
CP_FG_RED = 0x0004,
CP_FG_MAGENTA = 0x0005,
CP_FG_BROWN = 0x0006,
CP_FG_LIGHTGRAY = 0x0007,
CP_FG_GRAY = 0x0008,
CP_FG_LIGHTBLUE = 0x0009,
CP_FG_LIGHTGREEN = 0x000a,
CP_FG_LIGHTCYAN = 0x000b,
CP_FG_LIGHTRED = 0x000c,
CP_FG_LIGHTMAGENTA = 0x000d,
CP_FG_YELLOW = 0x000e,
CP_FG_WHITE = 0x000f,
CP_BG_BLUE = BACKGROUND_BLUE,
CP_BG_GREEN = BACKGROUND_GREEN,
CP_BG_RED = BACKGROUND_RED,
CP_BG_GRAY = BACKGROUND_INTENSITY,
#else // LINUX
CP_FG_BLACK = 0x0001,
CP_FG_RED = 0x0002,
CP_FG_GREEN = 0x0003,
CP_FG_YELLOW = 0x0004,
CP_FG_BLUE = 0x0005,
CP_FG_MAGENTA = 0x0006,
CP_FG_CYAN = 0x0007,
CP_FG_WHITE = 0x0008,
CP_FG_NULL = 0x000f,
CP_BG_BLACK = 0x0010,
CP_BG_RED = 0x0020,
CP_BG_GREEN = 0x0030,
CP_BG_YELLOW = 0x0040,
CP_BG_BLUE = 0x0050,
CP_BG_MAGENTA = 0x0060,
CP_BG_GYAN = 0x0070,
CP_BG_WHITE = 0x0080,
CP_BG_NULL = 0x00f0,
#endif
CP_DEF = 0x00ff,
};
/* Color-Print State */
struct cp_state
{
short default_color;
short current_color;
#ifdef WINDOWS
HANDLE std_output;
#else
FILE* std_output;
#endif
};
typedef struct cp_state* cp_state_ptr;
/* Module Functions */
cp_state_ptr cp_init();
int cp_print(cp_state_ptr, enum cp_color, const char * );
void cp_reset(cp_state_ptr );
void cp_close(cp_state_ptr );
#if defined(__cplusplus)
}
#endif
static int cp_apply(cp_state_ptr cp)
{
#ifdef WINDOWS
return SetConsoleTextAttribute(cp->std_output, cp->current_color) == TRUE ? 0:(-1);
#else
if (cp->current_color == CP_DEF)
return (fprintf(cp->std_output, "\e[0m") > 0) ? 0:(-1);
int cp_fg = ((cp->current_color & 0x0f) < 0x0f) ? (cp->current_color & 0x0f)+29 : 0;
int cp_bg = (((cp->current_color >> 4) & 0x0f) < 0x0f) ? ((cp->current_color >> 4) & 0x0f)+39 : 0;
if (cp_fg > 0)
if (fprintf(cp->std_output, "\e[%dm\e[%dm", cp_fg, cp_bg) < 0)
return (-1);
if (cp_bg > 0)
if (fprintf(cp->std_output, "\e[%dm", cp_fg) < 0)
return (-1);
#endif
}
cp_state_ptr cp_init()
{
cp_state_ptr cp;
cp = (cp_state_ptr)malloc(sizeof(struct cp_state));
assert(cp);
#ifdef WINDOWS
HANDLE std_output;
CONSOLE_SCREEN_BUFFER_INFO screen_buff;
std_output = GetStdHandle(STD_OUTPUT_HANDLE);
if (std_output == INVALID_HANDLE_VALUE)
return 0;
if(!GetConsoleScreenBufferInfo(std_output, &screen_buff))
return 0;
cp->std_output = std_output;
cp->default_color = cp->current_color = screen_buff.wAttributes;
#else
cp->std_output = stdout;
cp->default_color = cp->current_color = CP_DEF;
#endif
return cp;
}
int cp_print(cp_state_ptr cp, enum cp_color color, const char * text)
{
int ret;
assert(cp);
cp->current_color = color;
cp_apply(cp);
ret = printf("%s", text);
cp_reset(cp);
return ret;
}
void cp_reset(cp_state_ptr cp)
{
assert(cp);
cp->current_color = cp->default_color ;
cp_apply(cp);
}
void cp_close(cp_state_ptr cp)
{
assert(cp);
cp_reset(cp);
if (cp)
{
free(cp);
cp = NULL;
}
}
#endif /* __COLOR_PRINT_H__ */
<file_sep>#include "color_print.hpp"
#include <iostream>
int main(int argc, char *argv[])
{
typedef struct{
enum cp_color color;
const char * text;
} out_struct;
unsigned int i = 0;
out_struct sample[]={
{CP_FG_RED,"Red Text\n"},
{CP_FG_BLUE,"Blue Text\n"},
{CP_FG_GREEN,"Green Text\n"},
{CP_FG_YELLOW,"Yellow Text\n"},
{CP_BG_RED,"CP_BG_RED Text\n"},
{CP_BG_BLUE,"CP_BG_BLUE Text\n"},
{CP_BG_GREEN,"CP_BG_GREEN Text\n"},
// {CP_FG_GREEN | CP_BG_RED,"CP_FG_WHITE | CP_BG_RED Text\n"}
};
for (i = 0; i < sizeof(sample)/sizeof(out_struct); ++i)
{
std::cout << ColorPrint(sample[i].color, sample[i].text)
<< "-------------------------------" << std::endl;
printf("Normal Text\n");
}
return 0;
}
<file_sep>#ifndef __COLOR_PRINT_HPP__
#define __COLOR_PRINT_HPP__
#include <iostream>
#include <string>
#if defined __WIN32 || defined __WIN64 || defined WIN32 || defined WIN64
#ifndef WINDOWS
#define WINDOWS
#endif
// other platform
#endif
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef WINDOWS
#include <windows.h>
#else
#define TRUE true
#endif
/* Colors */
enum cp_color {
#ifdef WINDOWS
CP_FG_BLACK = 0x0000,
CP_FG_BLUE = 0x0001,
CP_FG_GREEN = 0x0002,
CP_FG_CYAN = 0x0003,
CP_FG_RED = 0x0004,
CP_FG_MAGENTA = 0x0005,
CP_FG_BROWN = 0x0006,
CP_FG_LIGHTGRAY = 0x0007,
CP_FG_GRAY = 0x0008,
CP_FG_LIGHTBLUE = 0x0009,
CP_FG_LIGHTGREEN = 0x000a,
CP_FG_LIGHTCYAN = 0x000b,
CP_FG_LIGHTRED = 0x000c,
CP_FG_LIGHTMAGENTA = 0x000d,
CP_FG_YELLOW = 0x000e,
CP_FG_WHITE = 0x000f,
CP_BG_BLUE = BACKGROUND_BLUE,
CP_BG_GREEN = BACKGROUND_GREEN,
CP_BG_RED = BACKGROUND_RED,
CP_BG_GRAY = BACKGROUND_INTENSITY,
#else // LINUX
CP_FG_BLACK = 0x0001,
CP_FG_RED = 0x0002,
CP_FG_GREEN = 0x0003,
CP_FG_YELLOW = 0x0004,
CP_FG_BLUE = 0x0005,
CP_FG_MAGENTA = 0x0006,
CP_FG_CYAN = 0x0007,
CP_FG_WHITE = 0x0008,
CP_FG_NULL = 0x000f,
CP_BG_BLACK = 0x0010,
CP_BG_RED = 0x0020,
CP_BG_GREEN = 0x0030,
CP_BG_YELLOW = 0x0040,
CP_BG_BLUE = 0x0050,
CP_BG_MAGENTA = 0x0060,
CP_BG_GYAN = 0x0070,
CP_BG_WHITE = 0x0080,
CP_BG_NULL = 0x00f0,
#endif
CP_DEF = 0x00ff,
};
class ColorPrint
{
private:
/* Color-Print State */
struct cp_state
{
short default_color;
short current_color;
#ifdef WINDOWS
HANDLE std_output;
#else
FILE* std_output;
#endif
};
typedef struct cp_state* cp_state_ptr;
/* Module Functions */
cp_state_ptr cp_init();
int cp_print(cp_state_ptr, enum cp_color, const char * ) const;
void cp_reset(cp_state_ptr ) const;
void cp_close(cp_state_ptr ) const;
public:
ColorPrint();
ColorPrint(cp_color color, const char* text);
ColorPrint(cp_color color, const std::string text);
virtual ~ColorPrint();
friend int cp_apply(cp_state_ptr cp);
friend std::ostream& operator<<(std::ostream&, const ColorPrint&);
private:
static unsigned int _count;
cp_state_ptr _cp;
cp_color _color;
std::string _text;
};
unsigned int ColorPrint::_count = 0;
ColorPrint::ColorPrint() : _color(CP_DEF), _text("")
{
if (((_count)++) == 0)
_cp = cp_init();
}
ColorPrint::ColorPrint(cp_color color, const char* text) : _color(color), _text(text)
{
if (((_count)++) == 0)
_cp = cp_init();
}
ColorPrint::ColorPrint(cp_color color, const std::string text) : _color(color), _text(text)
{
if (((_count)++) == 0)
_cp = cp_init();
}
ColorPrint::~ColorPrint()
{
if ((--(_count)) == 0)
cp_close(_cp);
}
std::ostream& operator<<(std::ostream& os, const ColorPrint& c)
{
c.cp_print(c._cp, c._color, c._text.c_str());
return os;
}
int cp_apply(ColorPrint::cp_state_ptr cp)
{
#ifdef WINDOWS
return SetConsoleTextAttribute(cp->std_output, cp->current_color) == TRUE ? 0:(-1);
#else
if (cp->current_color == CP_DEF)
return (fprintf(cp->std_output, "\e[0m") > 0) ? 0:(-1);
int cp_fg = ((cp->current_color & 0x0f) < 0x0f) ? (cp->current_color & 0x0f)+29 : 0;
int cp_bg = (((cp->current_color >> 4) & 0x0f) < 0x0f) ? ((cp->current_color >> 4) & 0x0f)+39 : 0;
if (cp_fg > 0)
if (fprintf(cp->std_output, "\e[%dm\e[%dm", cp_fg, cp_bg) < 0)
return (-1);
if (cp_bg > 0)
if (fprintf(cp->std_output, "\e[%dm", cp_fg) < 0)
return (-1);
#endif
}
ColorPrint::cp_state_ptr ColorPrint::cp_init()
{
cp_state_ptr cp;
cp = (cp_state_ptr)malloc(sizeof(struct cp_state));
assert(cp);
#ifdef WINDOWS
HANDLE std_output;
CONSOLE_SCREEN_BUFFER_INFO screen_buff;
std_output = GetStdHandle(STD_OUTPUT_HANDLE);
if (std_output == INVALID_HANDLE_VALUE)
return 0;
if(!GetConsoleScreenBufferInfo(std_output, &screen_buff))
return 0;
cp->std_output = std_output;
cp->default_color = cp->current_color = screen_buff.wAttributes;
#else
cp->std_output = stdout;
cp->default_color = cp->current_color = CP_DEF;
#endif
return cp;
}
int ColorPrint::cp_print(cp_state_ptr cp, enum cp_color color, const char * text) const
{
int ret;
assert(cp);
cp->current_color = color;
cp_apply(cp);
ret = printf("%s", text);
cp_reset(cp);
return ret;
}
void ColorPrint::cp_reset(cp_state_ptr cp) const
{
assert(cp);
cp->current_color = cp->default_color ;
cp_apply(cp);
}
void ColorPrint::cp_close(cp_state_ptr cp) const
{
assert(cp);
cp_reset(cp);
if (cp)
{
free(cp);
cp = NULL;
}
}
#endif /* __COLOR_PRINT_HPP__ */
<file_sep>###Usage
```c
#include "color_print.h"
/* Initialize color-print module */
cp_state_ref cp = cp_init();
/* Print text */
cp_print(cp,CP_RED,"Red Text\n");
/*Close color-print module */
cp_close(cp);
```
<file_sep>#include <stdio.h>
#include "color_print.h"
int main(int argc, char *argv[])
{
typedef struct{
enum cp_color color;
const char * text;
} out_struct;
unsigned int i = 0;
out_struct sample[]={
{CP_FG_RED,"Red Text\n"},
{CP_FG_BLUE,"Blue Text\n"},
{CP_FG_GREEN,"Green Text\n"},
{CP_FG_YELLOW,"Yellow Text\n"},
{CP_BG_RED,"CP_BG_RED Text\n"},
{CP_BG_BLUE,"CP_BG_BLUE Text\n"},
{CP_BG_GREEN,"CP_BG_GREEN Text\n"},
{CP_FG_GREEN | CP_BG_RED,"CP_FG_WHITE | CP_BG_RED Text\n"}
};
cp_state_ptr cp = cp_init();
for (i = 0; i < sizeof(sample)/sizeof(out_struct); ++i)
{
cp_print(cp, sample[i].color, sample[i].text);
printf("Normal Text\n");
}
cp_close(cp);
return 0;
}
<file_sep>#include "../Socket.h"
#include <iostream>
#include <string>
using namespace std;
#define IP "127.0.0.1"
// #define IP "10.14.5.107"
#define PORT 12345
int main(void)
{
try
{
cout << "-------- Simple prototype --------" << endl;
// Simple prototype
Socket::TCP client;
client.open();
client.bind_on_port(0);
client.connect_to(Socket::Address(IP, PORT));
string str_buffer;
cout << "input message to send: ";
cin >> str_buffer;
client.send_timeout<char>(1000, str_buffer.c_str(), str_buffer.length());
// client.send<char>(str_buffer.c_str(), str_buffer.length());
client.close();
cout << "Client close\n";
}
catch (Socket::SocketException &e)
{
cout << e.what() << endl;
}
try
{
cout << endl
<< "-------- Multi I/O prototype --------" << endl
<< "Any key to continue ...";
getchar();
getchar();
// Multi I/O prototype
Socket::TCP client;
client.open();
client.connect_to(Socket::Address(IP, PORT));
string str_buffer;
while (1)
{
cout << "input message string: ";
if (!(cin >> str_buffer))
break;
client.send(str_buffer.c_str(), str_buffer.length());
cout << "Local address: " << client.get_ip() << ":" << client.get_port() << endl;
}
client.close();
}
catch (Socket::SocketException &e)
{
int lasterror;
string err_msg;
if ((lasterror = e.get_error(err_msg)) > 0)
cout << "lasterror = " << lasterror << ", " << err_msg << endl;
cout << e.what() << endl;
}
return 0;
}
<file_sep>#include <iostream>
#include <sstream>
#include <vector>
#include <thread>
#if defined __WIN32 || defined __WIN64 || defined WIN32 || defined WIN64
#define WINDOWS
#endif
#ifdef WINDOWS
#include <windows.h>
#endif
#include "../ThreadPool.h"
#define MAX_BOARDSIZE 2048
#define BOARDSIZE 8
#define THREAD_NUM 4
using namespace std;
double get_current_performance_timer()
{
#ifdef WINDOWS
LARGE_INTEGER large_interger;
double freq, c;
QueryPerformanceFrequency(&large_interger);
freq = large_interger.QuadPart;
QueryPerformanceCounter(&large_interger);
c = large_interger.QuadPart;
return (c / freq);
#else
return clock();
#endif
}
void place_queens_multithread(size_t board_size = BOARDSIZE, unsigned int thread_num = THREAD_NUM);
class Queens
{
friend void place_queens_multithread(size_t, unsigned int);
private:
vector<int> _chessboard;
size_t _board_size;
vector<int> _column_flag, _slash1_flag, _slash2_flag;
void _print_board(ostream& os)
{
stringstream ss;
for (auto pos : _chessboard)
ss << string(2*pos, '_') << "##" << string(2*(_board_size - pos - 1), '_') << "\n";
ss << "\n";
os << ss.str();
};
void _place_nrow_queen(int row, ostream& os)
{
for (size_t col = 0; col < _board_size; ++col)
{
if (_column_flag[col] == 1
|| _slash1_flag[row + col] == 1
|| _slash2_flag[row - col + _board_size - 1] == 1)
continue;
_chessboard[row] = col;
_column_flag[col] = 1;
_slash1_flag[row + col] = 1;
_slash2_flag[row - col + _board_size - 1] = 1;
if (row > 0)
_place_nrow_queen(row - 1, cout);
else
_print_board(os);
// backtrak
_chessboard[row] = -1;
_column_flag[col] = 0;
_slash1_flag[row + col] = 0;
_slash2_flag[row - col + _board_size - 1] = 0;
}
};
public:
Queens(size_t board_size = BOARDSIZE)
{
if (board_size > MAX_BOARDSIZE)
_board_size = MAX_BOARDSIZE;
else
_board_size = board_size;
_chessboard.resize(board_size, -1);
_column_flag.resize(board_size, 0);
_slash1_flag.resize(2*board_size - 1, 0);
_slash2_flag.resize(2*board_size - 1, 0);
};
virtual ~Queens() {};
void place_all_queens()
{
// _place_nrow_queen(_board_size - 1, cout);
for (unsigned int col = 0; col < _board_size; ++col)
{
_chessboard[_board_size - 1] = col;
_column_flag[col] = 1;
_slash1_flag[_board_size - 1 + col] = 1;
_slash2_flag[_board_size - 1 - col + _board_size - 1] = 1;
_place_nrow_queen(_board_size - 2, cout);
_chessboard[_board_size - 1] = -1;
_column_flag[col] = 0;
_slash1_flag[_board_size - 1 + col] = 0;
_slash2_flag[_board_size - 1 - col + _board_size - 1] = 0;
}
};
};
void place_queens_multithread(size_t board_size, unsigned int thread_num)
{
ThreadPool pool(thread_num);
for (unsigned int col = 0; col < board_size; ++col)
{
pool.enqueue([&] () {
Queens queens(board_size);
queens._chessboard[board_size - 1] = col;
queens._column_flag[col] = 1;
queens._slash1_flag[board_size - 1 + col] = 1;
queens._slash2_flag[board_size - 1 - col + board_size - 1] = 1;
queens._place_nrow_queen(board_size - 2, cout);
});
}
};
int main(int argc, char *argv[])
{
int n;
cout << "input n: ";
cin >> n;
auto start1 = get_current_performance_timer();
Queens test_queens(n);
test_queens.place_all_queens();
auto end1 = get_current_performance_timer();
cout << "input n: ";
cin >> n;
auto start2 = get_current_performance_timer();
place_queens_multithread(n, 8);
auto end2 = get_current_performance_timer();
cout << "time: " << end1 - start1 << endl;
cout << "time: " << end2 - start2 << endl;
return 0;
}
|
eb81aa223f8e1b64da3e08ac0ade806d35cd2511
|
[
"Markdown",
"C++",
"C"
] | 7 |
Markdown
|
zhenglinj/Common
|
7f569ae318d02f1a01ea8b0715b2e884414231a4
|
14e103f5858f1359476288e8b4d2b79b350c5ac5
|
refs/heads/main
|
<file_sep># Given a numerical PIN, finds all possible combinations of telephone keypad letter equivalents.
# Please see the image in this repository for an example of such a keypad.
# This program assumes that any given digit can correspond to any of its assigned letters.
# This program does not account for multiple presses of a keypad number cycling through its assigned letters.
from itertools import product
# retrieves the appropriate letter corresponding to the entered number based on an index
def letterFetch(num, counter):
if num == 0:
return "_"
elif num == 1:
return "_"
elif num == 2:
if counter == 0:
return "A"
elif counter == 1:
return "B"
elif counter == 2:
return "C"
elif counter == 3:
return
elif num == 3:
if counter == 0:
return "D"
elif counter == 1:
return "E"
elif counter == 2:
return "F"
elif counter == 3:
return
elif num == 4:
if counter == 0:
return "G"
elif counter == 1:
return "H"
elif counter == 2:
return "I"
elif counter == 3:
return
elif num == 5:
if counter == 0:
return "J"
elif counter == 1:
return "K"
elif counter == 2:
return "L"
elif counter == 3:
return
elif num == 6:
if counter == 0:
return "M"
elif counter == 1:
return "N"
elif counter == 2:
return "O"
elif counter == 3:
return
elif num == 7:
if counter == 0:
return "P"
elif counter == 1:
return "Q"
elif counter == 2:
return "R"
elif counter == 3:
return "S"
elif num == 8:
if counter == 0:
return "T"
elif counter == 1:
return "U"
elif counter == 2:
return "V"
elif counter == 3:
return
elif num == 9:
if counter == 0:
return "W"
elif counter == 1:
return "X"
elif counter == 2:
return "Y"
elif counter == 3:
return "Z"
def main():
# variable for selecting calculation option
pin = input("Enter the 4-number PIN with the digits separated by spaces: ")
# list to hold the indicies for number selection
letterPicker = []
# list of tuples containing every combination of indicies
counters = product([0, 1, 2, 3], repeat = 4)
# splits the entered digits to be handled one at a time
digits = pin.split()
# for every combination of indicies
for i in list(counters):
# covert tuples to lists
letterPicker = list(i)
# completed, valid alphabetical equivalent PIN
finalAlpha = ""
# for every digit in the PIN
for k in range(4):
# convert the number from letterPicker and the correct index from the current list combination of indicies
finalAlpha += str(letterFetch(int(digits[k]), letterPicker[k]))
# for non-7 or non-9 digits that do not have a fourth letter, clear finalAlpha to prevent invalid output
if (digits[k] != 7 or digits[k] != 9) and letterPicker[k] == 3:
finalAlpha = ""
break
# avoid printing blank finalAlpha's
if finalAlpha == "":
continue
# display a completed, valid alphabetical equivalent PIN
print(finalAlpha)
main()
<file_sep># keypad-number-to-letter
Given a numerical PIN, finds all possible combinations of telephone keypad letter equivalents.
For example, "4444" could be "GGGG", "HIHI", etc.
Please see the image in this repository for an example of such a keypad.
This program assumes that any given digit can correspond to any of its assigned letters.
This program does not account for multiple presses of a keypad number cycling through its assigned letters.
|
d9b505452fa1527185215a9e433d88fb22b23b46
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
pdimagiba/keypad-number-to-letter
|
8ca8e7baba944c1e5179ffcdbe77ece9d46315b2
|
a8957d6b5ba2744b9d7df05b93ddbdce9208cc18
|
refs/heads/master
|
<repo_name>Merhawir8/todo-list<file_sep>/src/App.js
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import React, {useState} from 'react';
import { ListGroupItem, NavItem } from 'react-bootstrap';
// import Form from './components/Form';
export default () => {
const [inputVal, setInputVal] = useState("");
const [list, setList] = useState([]);
const add = e => {
e.preventDefault();
//make sure we do not input empty tasks
if(inputVal === "") return;
//set list, copy over the list and add a task obj with text and a boolean completed
setList([...list, {
text: inputVal,
completed: false
}]);
//rest the input field
setInputVal("")
}
const toggleChecked = index => {
const listItemToBeChanged = {
...list[index]
};
// we want the one to turn on or off
listItemToBeChanged.completed = !listItemToBeChanged.completed
// we are saying if it is true, now it is false vice versa
// we want to put the item back in it its place
setList([
...list.slice(0,index),
// this is the beginning to the index
listItemToBeChanged,
// then we are adding if it in the third position
...list.slice(index +1)
// then we are adding the rest of the index
])
}
const remove = index => {
setList(list.filter((_listObj, i) => i !== index))
}
return (
<div className="col-4 mx-auto card my-3" style={{backgroundColor:"peachpuff"}}>
<div className="card-header">
<h3>what is the plan for today?!</h3>
</div>
<form className="form-group" onSubmit={add}>
<input
type="text"
name="todo"
className="form-control"
onChange={e => setInputVal(e.target.value)}
value={inputVal}
/>
<div>
<button className="btn btn-outline-primary btn-sm m-2 p-2">Add</button>
</div>
</form>
{list.map( (listItemObject, index) =>(
<div key={index}>
<span
className="m-2"
style={{ textDecoration: listItemObject.completed && 'line-through'}}>{listItemObject.text}</span>
{/* this allows the inputVal to show under the add button */}
<input
type="checkbox"
checked={listItemObject.completed}
onClick={ () => toggleChecked(index)}
/>
<button
className=".btn.btn-outline-danger.btn-sm m-1 p-2"
onClick={ () => remove(index)}
>Delete
</button>
</div>
))}
</div>
);
}
|
2dfa299e08ea401415876450e0593965c918d3a3
|
[
"JavaScript"
] | 1 |
JavaScript
|
Merhawir8/todo-list
|
6b9fbdaa66f6f1e9029a4d554edc3d8af4736c1d
|
810b9dc7580dd3a5185949a319895d7a3121a4c2
|
refs/heads/master
|
<repo_name>Akintola-Stephen/stock-market-prediction-web-application<file_sep>/prediction/migrations/0002_remove_stock_stock_final_price.py
# Generated by Django 3.0.1 on 2021-02-19 00:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('prediction', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='stock',
name='stock_final_price',
),
]
<file_sep>/prediction/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('predict/', views.index, name='predicting-stock'),
path('stock-list/', views.stock_list, name='stock-list'),
]
<file_sep>/prediction/migrations/0001_initial.py
# Generated by Django 3.0.1 on 2021-02-18 22:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Stock',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('stocker', models.CharField(max_length=50)),
('stock_date', models.DateField()),
('stock_price', models.FloatField()),
('stock_high', models.FloatField()),
('stock_low', models.FloatField()),
('no_shares', models.FloatField()),
('stock_final_price', models.FloatField()),
],
),
]
<file_sep>/prediction/views.py
from django.shortcuts import render, redirect
from django.core.paginator import Paginator
from .models import Stock
import numpy as np
import pandas as pd
import joblib
# Create your views here.
def index(request):
if request.method == 'POST':
stock = Stock()
stock.stocker = request.POST.get('s_n')
stock.stock_date = request.POST.get('s_d')
stock.stock_price = request.POST.get('s_o')
stock.stock_high = request.POST.get('s_h')
stock.stock_low = request.POST.get('s_l')
stock.no_shares = request.POST.get('s_t')
user_data = np.array(
[
[
stock.stock_price, stock.stock_high,
stock.stock_low, stock.no_shares
]
]).reshape(1, 4)
model_path = 'ML/code/code folder/model.pkl'
ar = joblib.load(open(model_path, 'rb'))
prediction = ar.predict(user_data)
stock.stock_final_price = round(prediction[0], 2)
stock.save()
# return redirect('stock-list')
return redirect(request, 'home/stock_market.html')
def stock_list(request, template_name='home/stock-list.html'):
# noinspection PyUnresolvedReferences
# fetch the list of every predicted stock in the database
stock_lists = Stock.objects.all()
paginator = Paginator(stock_lists, 5)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, template_name, {'object_list': stock_lists, 'page_obj': page_obj})
<file_sep>/prediction/models.py
from django.db import models
# Create your models here.
class Stock(models.Model):
stocker = models.CharField(max_length=50)
stock_date = models.DateField()
stock_price = models.FloatField()
stock_high = models.FloatField()
stock_low = models.FloatField()
no_shares = models.FloatField()
stock_final_price = models.FloatField()
<file_sep>/prediction/migrations/0003_stock_stock_final_price.py
# Generated by Django 3.0.1 on 2021-02-19 00:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('prediction', '0002_remove_stock_stock_final_price'),
]
operations = [
migrations.AddField(
model_name='stock',
name='stock_final_price',
field=models.FloatField(default=625182),
preserve_default=False,
),
]
<file_sep>/ML/code/code folder/stock_code.py
import numpy as np
import pandas as pd
import joblib
import warnings
warnings.filterwarnings('ignore')
csv_path = 'stock-market-prediction-web-application/stock_prediction/ML/code/dataset/all_stocks_5yr.csv'
df = pd.read_csv(csv_path)
print(df.shape)
df['open'] = df['open'].fillna(df['open'].mean())
df['high'] = df['high'].fillna(df['high'].mean())
df['low'] = df['low'].fillna(df['low'].mean())
print(df.isna().sum() / len(df))
drop_cols = ['date', 'Name']
df.drop(drop_cols ,axis = 1, inplace = True)
cols = ['open', 'high', 'low', 'close']
X = df[cols]
y = df['volume']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
print(
'X_train shape and X_test are {0} {1} respectively'
'while y_train and y_test shape are {2} {3}'.format(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
)
from sklearn.linear_model import ARDRegression
ar = ARDRegression()
ar.fit(X_train, y_train)
print(ar.score(X_train, y_train))
prediction = ar.predict(X_train)
joblib.dump(ar, 'model.pkl')
|
af1f35ea91124e60079c20e71ae33be6b53fb4f6
|
[
"Python"
] | 7 |
Python
|
Akintola-Stephen/stock-market-prediction-web-application
|
5f5de19c9f850baa13506a1210e4808b98ae7ce2
|
09f6f5ed60193f4807008e9d2b74cc73b50ff1dd
|
refs/heads/master
|
<file_sep># CHAPTER 1
## Introduction
**1. Got to know a little bit more what does it mean:**
+ *http//: or https//:*
+ *doman name*
+ *doman zone*
+ *URL*
+ *host*
**2. Downloaded Microsoft Visual Studio Code;**
**3. Made an account on [github](https://github.com/kopakonan) and uploaded my first own directorie;**
**4. Markdown syntax ->**
**[useful link](https://learnxinyminutes.com/docs/ru-ru/markdown-ru/#horizontal-rule)**
|
dd465cb60d39313a5191b7ab9d3bcb2c25255bb4
|
[
"Markdown"
] | 1 |
Markdown
|
kopakonan/BYOW
|
720ad569d28d7c69768e626164f0544d4f7373a7
|
620f73844fb46e4b392d0b05e3c56e48a547cdcd
|
refs/heads/main
|
<file_sep># decision-tree--classifier
|
b98a12462967e99f7181490bc94018f675c408a1
|
[
"Markdown"
] | 1 |
Markdown
|
chaiDS/decision-tree--classifier
|
1b8994f4659f800a7451d7b14fd3a2c32b469173
|
64715597826be03f073c6b800242e80d914bfc53
|
refs/heads/master
|
<repo_name>michaelbyrd/sounds<file_sep>/README.md
# Setup
- open `index.html`
|
5f1e681516a67b1bae2bd961058b0f2f427095a9
|
[
"Markdown"
] | 1 |
Markdown
|
michaelbyrd/sounds
|
659c6b28b2a5864dc1f5fc21903368d122253b5c
|
6978fdc542a4a3e7d0990e4948fdb37dadef5416
|
refs/heads/master
|
<repo_name>tekeh/tekeh.github.io<file_sep>/_posts/2020-12-27-removing-bias.md
---
layout: post
title: Circumventing Bias
image: /img/hello_world.jpeg
tags: [probability, stub]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Suppose you have a coin which has probability $$p$$ of giving heads when it is flipped. If $$p \neq 1/2$$ then the coin is called _biased_. Despite the biased nature of the coin, it is still possible to use it to generate fair "flips".
Consider flipping the coin twice, independently. The sample space $$\mathcal{S} = \{ HH, HT, TH, TT\}$$ with probabilities, $$p^2, p(1-p), p(1-p), (1-p)^2$$. The two mixed results have equal probability, so to simulate an even RV, we merely flip twice and treat $$HT$$ as "tails" and $$TH$$ as "heads". If we get any other outcome we retry. This is called the _Von Neumann method_. Note that unlike in the case of a truly fair coin, this method has a running time which is not deterministic, and could (technically) go on forever. The expected running time, $$T$$, which is the number of flips, is ($$P=2p(1-p)$$)
$$
E(T) = \frac{1}{p(1-p)}
$$
with a variance given by
$$
{\rm VAR} (T) = \frac{1 - 2p(1-p)}{p^2(1-p)^2}
$$
This demonstrates that we can implement strategies which circumvent bias (at least in this case), but not necessarily efficiently.
<file_sep>/_posts/2021-04-08-curl-forces.md
---
layout: post
title: Hamiltonian Curl Forces
image: /img/hello_world.jpeg
tags: []
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
It is known that _conservative force_, defined as those which are the gradient of a scalar function, are curl free. This is a consequence of basic vector calculus
$$
\nabla \times {\bf F}_{\rm cons} = - \nabla \times \nabla V = 0
$$
The motion of a particle under conservative motion (motion arising under the action of a conservative force) can equally be described in the Hamiltonian mechanics framework (reviewed within [here](https://tekeh.github.io/2021-03-05-funky-symplectics/)). This Hamiltonian is most often in the form of kinetic terms + potential terms, namely
$$ \label{eq:hamiltonian} \tag{1}
\mathcal{H} = \frac{ {\bf p}^2}{2}+ V({\bf r})
$$
when considering just one particle in _d_-dim. Hamiltons equations give
$$
\dot{\bf r} = \frac{\partial \mathcal{H}}{\partial {\bf p}} = {\bf p}
$$
$$
\dot{\bf p} = -\frac{\partial \mathcal{H}}{\partial {\bf r}} = -\nabla V
$$
and when combined imply that the equaton of motion for $${\bf r}$$ alone is
$$ \label{eq:ode} \tag{2}
\ddot {\bf r} = -\nabla V({\bf r})
$$
Note this choice isn't unique - we could have easily defined, for example, the Hamiltonian
$$
\mathcal{H}' = \frac{ {\bf p'}^2}{2 \eta}+ \eta V({\bf r'})
$$
for constant $$\eta$$, which would also lead us to \eqref{eq:ode}. However, one should note that the definition of the conjugate momenta changes with this rewriting - the Hamiltonian still represents the systems true energy (up to a factor of $$\eta$$).
Some equations of motion, admittedly often arising from some effective description, may contain forces which are non-conservative. Clearly taking a Hamiltonian of the form of \eqref{eq:hamiltonian} can not lead to a force with a curl. Despite this the phase space of $${\bf r}$$ and $${\bf v = \dot r}$$ is still volume-preserving since
$$
\nabla_{\bf r} \dot {\bf r} + \nabla_{\bf v} \dot{\bf v} = \nabla_{\bf r} {\bf v} + \nabla_{\bf v} {\bf F}({\bf r}) = 0
$$
which is a statement of Liouville's theorem when the system is Hamiltonian with conjugate momenta given by $${\bf p = \dot r}$$, but holds despite the form of the conjugate momenta (or the existence of a Hamiltonian). Thus the dynamics are non-dissipative too. [2]
Can we create other forms of the Hamiltonian that will produce a desired (non curl-free) force? The answer is maybe. We can immediately see that there are some choices of Hamiltonian that give us forces with some amount of curl. Take for example the Hamiltonian in [1] with anisotropic kinetic energy
$$
\mathcal{H}_1 = \frac{1}{2} \alpha p_x^2 + \beta p_x p_y + \frac{1}{2} \gamma p_y^2 + V(x,y)
$$
The equation of motion for $${\bf r} = (x,y, z)$$ is
$$ \label{eq:curl-ode} \tag{3}
\ddot {\bf r} = - {\bf M} \nabla V \qquad {\rm where\ }\quad {\bf M} = \begin{pmatrix} \alpha & \beta & 0 \\
\beta & \gamma & 0 \\
0 & 0 & 0
\end{pmatrix}
$$
The $$z$$ directed curl is given by
$$
(\alpha - \gamma) \partial_{xy} V + \beta ( \partial_{yy} -\partial_{xx})V
$$
which is non zero for general $$V$$, so at least _some_ curl forces can be embedded in a Hamiltonian without doing crazy things like doubling the degrees of freedom. The Hamiltonian is obviously conserved throughout the dynamics. We confirm this by playing around with \eqref{eq:curl-ode}. Projecting down to $$(x,y)$$, and assuming $${\bf M}$$ invertible
$$
\begin{equation}
\begin{aligned}
{\bf M}^{-1} \ddot {\bf r} &= - \nabla V \\
\dot {\bf r} \cdot {\bf M}^{-1} \ddot {\bf r} &= - \dot {\bf r} \cdot \nabla V \\
\implies 0 &= \frac{d}{dt} \Big( \frac{1}{2} \dot{\bf r}^T {\bf M}^{-1} \dot {\bf r} + V({\bf r}) \Big)
\end{aligned}
\end{equation}
$$
which, after the identification of $$\dot {\bf r} = {\bf M} {\bf p}$$, is equivalent in form to the Hamiltonian.
Another pertinent example is of a **pure shear force**
$$
\ddot {\bf r} = f(y) {\bf e}_x
$$
This force has some curl for general $$f$$. Take
$$
\mathcal{H}_{\rm shear} = \frac{1}{2} p_{x}^2 + p_{y} v_{y}(0) - x f(y)
$$
Hamilton's equations yield
$$
\dot p_x = f(y) \qquad \dot x = p_x
$$
$$
\dot p_y = x f'(y) \qquad \dot y = v_y(0)
$$
which leads to
$$
\ddot x = f(y) \qquad \ddot y = 0
$$
as required. Again the Hamiltonian is conserved, although its form is sufficiently foreign that one is hesitant to use the term "energy" to describe its constant value. Can verify constancy directly
$$
\begin{equation}
\begin{aligned}
\dot{\mathcal{H}} &= \dot{p}_x p_x + \dot{p}_y v_y(0) - \dot{x} f(y) - \dot{y} x f'(y) \\
&= \dot{x} f(y) + x f'(y) v_y(0) -\dot{x} f(y) - v_y(0) x f'(y) \\
&= 0
\end{aligned}
\end{equation}
$$
The Hamiltonian has the peculiarity of depending on an initial condition.
A final example - **2-dim propelled motion**
$$
\ddot \theta = 0
$$
$$
\ddot {\bf r} = v {\bf n}(\theta) - \nabla V({\bf r})
$$
The dynamics is roughly that of a particle being pushed around at a constant self propulsion speed $$v$$, with an evolving angular direction $$\theta \in [0, 2\pi)$$.
Consider
$$
\mathcal{H}_{\rm prop} = \frac{1}{2} {\bf p \cdot p} + v_{\theta}(0) p_{\theta} - v {\bf r \cdot n} + V({\bf r})
$$
yielding
$$
\dot {\bf r} = {\bf p} \qquad \dot{\bf p} = v {\bf n} - \nabla V
$$
$$
\dot{\theta} = v_{\theta}(0) \qquad \dot{p}_{\theta} = - v {\bf r} \cdot {\bf e}_{\phi}(\theta)
$$
And yet again we have defined an effective Hamiltonian for the dynamics.
**[References]**
**1.** <NAME>. & Shukla, P. Hamiltonian curl forces. Proc. R. Soc. A. 471, 20150002 (2015).
**2.** <NAME>. & <NAME>. Classical dynamics with curl forces, and motion driven by time-dependent flux. J. Phys. A: Math. Theor. 45, 305201 (2012).
<file_sep>/_posts/2018-12-01-message-passing-1d.md
---
layout: post
title: Message Passing in 1D
image: /img/hello_world.jpeg
tags: [information theory, probability]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Suppose we have a 1D array of N spins on a ring, which can be either $$\uparrow$$ or $$\downarrow$$. Suppose further that we fix one of the $$N$$ previously identical spins such that it is $$\uparrow$$. Now inagine that between each pair of spins is a directed information channel that aims to transfer the value of each spin to it's neighbour. All the channels are noisy with the same statistics, and because of this the input spin will have a probability $$f$$ of being flipped (independent of which way up it is).
So we start with a spin $$\uparrow$$ at position $$0$$ and try to transmit this spin along the channels. Once we've got to the $$N-1$$th position we have some ordering of spins. What is the probability of seeing a specific spin configuration?
Let us define a state vector $$\boldsymbol{b} = (p_{ \uparrow }, p_{ \downarrow })$$ which describes the probability of being in a certain spin state. Further define $${\bf b}_{\uparrow}$$ and $${\bf b}_{\downarrow}$$ to be the state of being up or down with certainty, respectively. After going through one of the channels we have the following recursion between spins on neighbouring sites
$$ \boldsymbol{b}_n = W \boldsymbol{b}_{n-1} \qquad \qquad \hat W = \pmatrix{1 - f & f \\ f & 1 - f} $$
Further, we can write down the probability of a certain spin configuration. For the configuration $$ [\Updownarrow] = \uparrow ...\uparrow \downarrow \uparrow s_0 \equiv s_N ... s_3 s_2 s_1 s_0$$ with the first spin rightmost, the probability is
$$ \mathcal{P} ( [ \Updownarrow ] \vert {\bf s}_0) = \prod_{k=1}^N \mathcal{P}({\bf s}_k \vert {\bf s}_{k-1}) = \prod_{k=1}^{N} {\bf s}_k^T \hat W {\bf s}_{k-1} = {\bf b}_{\uparrow}^T \hat W ... \hat W {\bf b}_{\uparrow} {\bf b}^T_{\uparrow} \hat W {\bf b}_{\downarrow} {\bf b}^T_{\downarrow} \hat W{\bf b}_{\uparrow} {\bf b}^T_{\uparrow} \hat W \boldsymbol{s}_0 $$.
Define $$W_{ss'} = {\bf s}^T \hat W {\bf s'}$$. Then we could equivalently write
$$ \mathcal{P}( [ \Updownarrow ] \vert \boldsymbol{s}_0) = W_{s_N s_{N-1}} W_{s_{N-1} s_{N-2}} ... W_{s_{1} s_0} $$
Note here that since the states each spin site $${\bf s}_k$$ can take are finite, so the new $$W_{ss'}$$ act as components of a matrix. The probability is necessarily normalised.
By marginalising our product we can write the probability of a spin at site $$k$$ given the value at site $$l < k$$ straightforwardly
$$
\mathcal{P}({\bf s}_k \vert {\bf s}_l) = {\bf s}_k W^{\vert k - l\vert} {\bf s}_l
$$
Okay.
If we think of this transfer probability as resulting from an effective channel, then what is the capacity of this channel? As a reminder, the capacity $$C$$ is the supremum of the mutual information $$I(X;Y)$$. This mutual information can be written explicitely (with some calculation)
$$
I({\bf s}_k; {\bf s}_l) = H_2\big(p_{\downarrow}^{l} [ 1 - g_{\vert k - l \vert}(\uparrow\uparrow)] + [1 - p_{\downarrow}^{l}] g_{\vert k-l \vert}(\uparrow\uparrow) \big) - H_2\big(g_{\vert k - l \vert}(\uparrow\uparrow) \big)
$$
Where $$g_x(ss') = {\bf b}_s W^x {\bf b}_{s'}$$. This is maximised using a uniform input distribution at site $$l$$, which leads to a capacity of
$$ C_{kl} = \sup_{\mathcal{P}({\bf s}_k)} I({\bf s}_k;{\bf s}_l) = 1 - H_2(g_{\vert k - l \vert}(\uparrow\uparrow)\big) $$
And we can also write $$g$$ on terms of the original flip probability for neighbours using a recursive method.
$$g_{\vert k - l \vert}(\uparrow\uparrow) = \frac{1}{2} (1 + (1-2f)^{\vert k - l \vert})$$
The <b>Data Processing Theorem</b> (DPT) , which says that the mutual information between input and output of an information channel should only decrease after going through more channels, so all this is consistent.
For an unbiased ising Hamiltonian $$ - \beta \mathcal{H} = K \sum s_{i} s_{i+1}$$ the transfer matrix form of the Boltzmann distribution takes the form
$$ \mathcal{P}_{\text{Boltz}}( [ \Updownarrow ] ) = \frac{T_{s_0 s_1} T_{s_1 s_2} ... T_{s_{N-1} s_N} }{\mathcal{Z}} \qquad T = \pmatrix{e^{K} & e^{-K} \\ e^{-K} & e^{K}}$$
$$f$$, which is a measure of the information channel noise, should therefore be related to the spin coupling, and we can basically just see that $$ f = \frac{1}{1 + e^{2K}} = n_{\text{Fermi}}(2K) $$. So if $$f < 1/2$$ (good transmission) then the chain is ferromagnetic whereas if $$f > 1/2 $$ (poor transmission) then the chain is antiferromagnetic. The extremes also makes sense in this correspondence.
This is all just set up for tackling the case of 2D.
References:
[1] <NAME>, <i> Information Theory, Inference, and Learning Algorithms </i>
[2] <NAME>, <i> Exactly Solved Models in Statistical Mechanics </i>
<file_sep>/_posts/2019-02-15-gaussian-mixture.md
---
layout: post
title: Gaussian Mixtures
image: /img/hello_world.jpeg
tags: [stochastic processes]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Arguably one of the simplest, nicest to work with distributions is that of a Gaussian. Within the field of stochastic ODEs, the common stochastic noise (the Weiner process) is simply a Guassian distributed point process. But depending on the system in question, a systems noise could be distributed differently. Some of these cases are of interest, as they can describe the breaking of fluctaution dissipation and memory effects in stochastic systems. The point here is that if the system is linear then the problem is no harder if we can represent the noise as some linear combination of gaussian point processes.
Let us consider the most basic example. Consider the single variable stochastic system
$$ dx_t = \lambda + \mu x_t dt + d \Pi_t $$
$$d \Pi$$ is a stationary stochastic noise, but can be a peculiar one. It isn;t distributed according to a gaussian, but instead it follows some general symmetric distribution $$\mathcal{P}(d \Pi_t = x) = \rho(x) $$. What we want to be able to do is find some continuous superposition of functions of zero mean gaussians which mimic $$\rho$$. i.e
$$ \int_{0}^{\infty} f_L(\beta) e^{- \beta x^2 /2}\frac{d\beta}{\sqrt{2 \pi \beta^{-1}}} = \rho(x) \label{eqn:integral_f} \tag{1} $$
We also want to derive conditions for when this is even possible. But first let's do a quick example to be clear.
<h3> Example: Lorentzian Distribution </h3>
Suppose we wanted to represent a Lorentzian distribution in this manner. The Lorentzian pdf is well known and corresponds to a <b>Cauchy Process</b>, which is a discontinuous jump process.
$$ \int_{0}^{\infty} f_L(\beta) e^{- \beta x^2 /2}\frac{d\beta}{\sqrt{2 \pi \beta^{-1}}} = \frac{1}{\pi} \frac{\delta}{x^2 + \delta^2} $$
After a few redefinitions we can write the same expression as
$$ \int_{0}^{\infty} F_{L}(\beta') e^{- \beta' s} d\beta ' = \frac{1}{\pi} \frac{\delta}{s + \delta^2} $$
We can spot the answer from here, either by inspection or noticing that this <b>Laplace Transform</b> is well known and it's inversion can be looked up in a table. This then gives that
$$F_L(\beta') = \frac{\delta}{\pi} e^{-\delta^2 \beta'} $$
which then leads to
$$ f_L(\beta) = \frac {\delta }{\sqrt{2 \pi}} \beta^{-1/2} e^{-\delta^2 \beta/ 2} = \Gamma(1/2, \delta/\sqrt{2})$$
This is Gamma distributed. It follows that we can calculate observables for a gaussian process with noise $$ \sqrt{2/\beta} dW_t$$ and then perform a secondary average over $$f_L(\beta)$$ (as long as the system is linear) to get the observables in the Cauchy process. From a simulation perspective, we can get the same behaviour by, at every timestep, randomly choosing $$\beta$$ according to $$f_L(\beta)$$. One way to think about it is having a system coupled to many different equilibrium heat baths with various strengths, which then gives rise to seemingly nonequilibrium noise behaviour. Below is a picture showing that we do indeed get a good mimic

With $$f_L$$ positive we could view it as a sort of meta ensemble of variances, or a <b> Superstatistical ensemble</b> to use a term coined by E Cohen. We could then simulate the process by seeing it as some kind of frequency for each variance over the simulation. Table 1 shows a table showing how to get define $$f(\beta)$$ in order to get certain target distributions. It shows that we can get some quite varied staitistical features, such as broad tails or exponential decay.
$$
\begin{array}{c|lcr}
\text{Behaviour} & \rho(x) & f(\beta) \\
\hline
\text{Laplace distribution} & c \exp(-c \vert x \vert )/2 & \propto \exp(-c^2/2 \beta)/c \beta^2 \\
\text{t-distribution} & \propto (1 + x^2/\nu)^{-(\nu + 1)/2} \sim \vert x \vert ^ {-\nu - 1} & \propto \beta^{\nu/2 -1} \exp(-\beta \nu/2) \\
\text{Lorentzian} & \delta (x^2 + \delta^2)^{-1}/\pi & \Gamma(1/2, \delta/\sqrt{2}) \\
\end{array}
$$
We can do better than just resorting to a lookup table or inspiration if we wish to get a certain target distribution. We can systematically construct a differential equation for $$f$$ given the target (if such an $$f$$ exists). for example suppose now we wish to create the <b> Exponential distribution </b>
$$
\int_{0}^{\infty} f_E(\beta) e^{- \beta x^2 /2}\frac{d\beta}{\sqrt{2 \pi \beta^{-1}}} = \frac{c \exp(- c \vert x \vert) }{2}
$$
We know that for $$x>0 $$ the RHS obeys the ODE $$ y'' - c^2y = 0 $$ (we only need to constrain half the distribution, as we automatically get something symmetric from the gaussian mixture construction). Therefore let us take a double $$x$$ derivative on both sides of the equation
$$
\int_{0}^{\infty} F_E(\beta) \big( - \beta + (- \beta x)^2 \big) e^{- \beta x^2 /2}d\beta = c^2 \int_{0}^{\infty} F_E(\beta) e^{- \beta x^2 /2} d\beta
$$
After intgerating the second term on the LHS by parts we then arrive at the expression
$$
\int_{0}^{\infty} \Big( (\beta + c^2) F_E(\beta) - 2 \partial_{\beta}(\beta^2 F_E) \Big)e^{- \beta x^2 /2} d\beta = 0
$$
This should be true for all $$x$$ so the integrand identically vanishes. This differential equation can be easily solved to give
$$ F_E(\beta) \propto \beta^{-3/2} \exp(-c^2/2\beta) \implies f_E \propto \beta^{-2} \exp(-c^2/2 \beta)$$
Purely positive $$f$$ has some limitations - it's clear that it could not mimic distributions with a local minimum at the origin, for example. There are even stronger limits. A basic fact to consider here is that the Laplace transform of a positive integrable function is always log-concave. If $$g$$ is such a function then directly from <b>Holder's Inequality</b> $$(1/p = \lambda, 1/q = 1 - \lambda)$$ we get
$$
\int_0^{\infty} g(t) e^{-[\lambda s_1 + (1 - \lambda) s_2] t } dt \leq \Bigg( \int_0^{\infty} g(t) e^{-s_1 t}dt \Bigg)^{\lambda} \Bigg( \int_0^{\infty} g(t) e^{-s_2 t} dt \Bigg)^{1 - \lambda}
$$
The natural next step would be to allow $$f$$ to go negative at some points to mimic some $$\rho$$ in the integral sense ( Eq \eqref{eqn:integral-f} ). But the RHS must always be positive. Two zero mean gaussians with $$\sigma_1$$ and $$\sigma_2$$ always have crossover points (Normalised gaussians do not envelope each other) so their difference will be negative in some region of space. This consideration shows us we need to have some restrictions on $$f$$ if we allow it negative.
What's more, letting $$f$$ be negative is still not sufficient to describe all functions of interest. As another example consider a symmetric bimodal distribution
$$ \int_{0}^{\infty} f_{BM}(\beta) e^{- \beta x^2 /2}\frac{d\beta}{\sqrt{2 \pi \beta^{-1}}} = \frac{1}{2 \sqrt{2 \pi \eta^{-1}}}\Big( e^{-\eta(x+\Delta)^2/2 } + e^{-\eta(x-\Delta)^2/2} \Big) $$
For this case, we'll fourier transform both sides in $$x$$. This then yield
$$ \int_{0}^{\infty} f_{BM}(\beta) e^{- \beta^{-1} k^2 /2} d\beta= e^{- \eta^{-1} k^2 /2} \cos (k \Delta) $$
$$ \int_0^{\infty} F_{BM}(\beta') e^{-\beta' s} d\beta' = \cos(\Delta \sqrt{s}) $$
More rearranging/shifting in the second line. But this equality can never be satisfied. If we look at the limit $$s \rightarrow \infty$$ then the LHS should go to 0 whereas the RHS has no defined limit.
References:
[1] <NAME>, <i> Handbook of Stochastic Methods </i>
[2] <NAME>, <NAME>, <i> Superstatististics </i>
<file_sep>/_posts/2020-12-11-stable-dists.md
---
layout: post
title: Stable Distributions
image: /img/hello_world.jpeg
tags: probability, statistics
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
From Wikipedia:
"Let $$X_1$$ and $$X_2$$ be independent copies of a random variable $$X$$. Then $$X$$ is said to be stable if for any constants $$a > 0$$ and $$b > 0$$ the random variable $$aX_1 + bX_2$$ has the same distribution as $$cX + d$$ for some constants $$c > 0$$ and $$d$$."
And the distribution of X is called a _stable distribution_.
Under convolution, these distributions are fixed points. Some examples come to mind immediately, such as the much loved Normal Distribution $$P_{\mathcal{N}}(x \vert \mu, \sigma^2)$$, which obeys the following relationship:
$$\begin{equation}
P_{\mathcal{N}}(x/a | \mu, \sigma^2) * P_{\mathcal{N}}(x/b | \mu, \sigma^2) = P_{\mathcal{N}}(x | (a+b) \mu, (a^2 + b^2) \sigma^2)
\end{equation}
$$
But other stable distributions exits, such as the Cauchy Distributions $$P_{\mathcal{C}}(x\vert \mu, \gamma)$$. We show this explicitely by Fourier Transforming and using the convolution theorem:
$$
\begin{equation}
\begin{aligned}
FT \Big[ P_{\mathcal{C}}(ax | \mu, \gamma^2) &* P_{\mathcal{C}}(bx | \mu, \gamma^2)\Big] (k) \qquad (a,b>0)\\
&= \phi_{\mathcal{C}}(k/a | \mu, \gamma^2 ) \cdot \phi_{\mathcal{C}}(k/b| \mu, \gamma^2 ) \\
&= e^{-i k \mu(a^{-1} + b^{-1}) - \gamma |k|(a^{-1} + b^{-1}) } \\
& = \phi_{\mathcal{C}} (k | \mu', \gamma'^2) \qquad (\mu', \gamma'^2) = (\mu(a^{-1}+b^{-1})^{-1}, \gamma'^2 = \gamma^2 (a^{-1} + b^{-1})^{-1} ) \\
\rightarrow P_{\mathcal{C}}(ax | \mu, \gamma^2) &* P_{\mathcal{C}}(bx | \mu, \gamma^2) = P_{\mathcal{C}}(x \vert \mu', \gamma' )
\end{aligned}
\end{equation}
$$
So again, the functional form is preserved - the normal distribution is not alone in this.
What make the enormal distribution even more powerful is the **Central Limit Theorem** (CLT) which says that the sum of $$N$$ IIDs with a finite mean and variance will converge in probability to a Gaussian as $$N \rightarrow \infty$$. This is a stronger statement, because it implies that no matter the distribution you start with, if the CLT holds then you will eventually get to the Gaussian as you do more convolutions. And once you "arrive" at the Gaussian, in the asymptotic sense, you will remain there, so it is an attractor in probability space, not just an unstable fixed point. So where does this leave all our other non-gaussian stable distributions? Are they ever reached when carrying out an asymptotic sum? The answer is yes, the CLT does not cover all cases - sums of iids without a defined variance (or mean) can converge to distributions other than the Gaussian.
## Stable distribution families
As said, the stable distributions are invariant, up to shifts and rescalings, under a convolution. It convenient to work in fourier space, where the relation reads
$$
\begin{equation}
\begin{aligned}
\tilde\rho(k a) \cdot \tilde\rho(k b) &= e^{i k \delta} \tilde\rho(k c) \\
\end{aligned}
\end{equation}
$$
First consider the case of no shift. Defining $$\hat f(x) = \ln(\tilde\rho(x)) $$. Then we wish to solve
$$
\begin{equation}
\hat f(ak) + \hat f(bk) = ik\delta + \hat f(ck)
\end{equation}
$$
where $$c = c(a,b)$$ is a constant depending on the scaling. Further define $$\hat f(x) = f(x) + ix\delta$$, which reduces the functional equation to a homogeneous form:
$$
\begin{equation}
f(ak) + f(bk) = f(ck)
\end{equation}
$$
Which holds for all real $$a, b, k$$, with an an adjoining $$c(a, b)$$. We can deduce properties by taking special points:
- 1) $$c(a,b) = c(b,a) \qquad (a \leftrightarrow b)$$
- 2) $$f(0) = 0 \qquad (k=0) $$
- 3) $$c(a, 0) = a \qquad (b=0)$$
- 4) $$f(a/b) - f(b/a) = f(c/b) - f(c/a) \qquad (k=1/a) - (k= 1/b) $$
- 5) $$ c( c(x, y), z) {\rm \ permutation\ invariant} \qquad (f(ak) +f(bk) + f(ck) ) $$
This seems tough to solve directly.
The issue was solved via other methods by those Kolmogorov and friends - the general solution is known, and is of the form
$$
\begin{equation}
f(k; \alpha, \beta, \gamma) = -\vert \gamma k \vert^{\alpha} ( 1 - i \beta {\rm sgn}(k) \Phi)
\end{equation}
$$
where
$$ \Phi = \begin{cases} \big( \vert \gamma k \vert^{1-\alpha} - 1 \big) \tan(\frac{\pi \alpha}{2}) \qquad \alpha \neq 1 \\
-\frac{2}{\pi} \log \vert \gamma k\vert \qquad \alpha=1\end{cases}
$$
$$\alpha, \beta, \gamma, \delta$$ are parameters of the distribution. $$\alpha \in (0,2]$$ is called the stability parameter, $$\beta \in [-1,1]$$ is a measure of the skewness and $$\gamma \in \mathbb{R}^{+} $$ is the scale parameter. Furthermore the parameter $$\delta$$ in $$\hat f$$ is called the _location parameter_. The normal distribution corresponds to $$\alpha =2$$, the only value of alpha which yields a distribution with a defined variance.
Although the characterstic function can be parametrised exactly, there is no general analytic form for the probability distribution - only special cases are known. The document [here](https://cds.cern.ch/record/1566201/files/978-3-319-00327-6_BookBackMatter.pdf) lists several closed forms for specific parameter values.
For a distribution $$P(x)$$ to belong to the basin of attraction for the stable distribution with parameter $$\alpha$$, it is necessary and sufficient for
- 1) $$\frac{P(-x)}{1 - P(x)} \rightarrow \frac{c_{-}}{c_{+}}, \qquad x\rightarrow \infty $$
- 2) $$\frac{1 - P(x) + P(-x)}{1 - P(kx) + P(kx)} \rightarrow k^{\alpha}, \qquad x\rightarrow \infty \qquad$$ for every $$k>0$$
where $$c_{-},c_{+}$$ are constants which are proportional to the amplitudes of the asymptotic behaviours of $$P(x)$$ for large $$\pm x$$ (defined with great specificity in Ref 4.). There are also independent conditions that rely on knowledge of the characteristic function.
Let $$p(k)$$ be the characteristic function of $$P(x)$$. To belong to the basin of attraction for the stable distribution with parameter $$\alpha$$, it is necessary and sufficient for
#### $$0<\alpha<2, \alpha \neq 1$$
$$
\begin{equation}
\lim_{r\rightarrow 0} \frac{\rm{Re}[\ln p(rk)]}{\rm{Re}[\ln p(r)]} = k \qquad
\end{equation}
$$
and
$$
\begin{equation}
\lim_{r\rightarrow 0} \frac{\rm{Im}[\ln p(rk)]}{\rm{Re}[\ln p(r)]} = \beta r^{\alpha} \tan\Big( \pi \alpha/2\Big) \qquad
\end{equation}
$$
#### $$\alpha = 1$$
$$
\begin{equation}
\lim_{r\rightarrow 0} \frac{\rm{Re}[\ln p(rk)]}{\rm{Re}[\ln p(r)]} = k \qquad
\end{equation}
$$
and
$$
\begin{equation}
\lim_{r\rightarrow 0} \frac{\rm{Im}[\ln e^{-i\langle x \rangle rk} p(rk) - r\ln e^{-i\langle x \rangle k} p(k)]}{\rm{Re}[ \ln e^{-i\langle x \rangle r} p(r)]} = \frac{2 \beta}{\pi} k\ln k
\end{equation}
$$
**[References]**
[1] [Wiki](https://en.wikipedia.org/wiki/Stable_distribution) (Last accessed: 21 Nov 2020)
[2] [Random Services](http://www.randomservices.org/random/special/Stable.html) (Last accessed: 21Nov2020)
[3] [https://cds.cern.ch/record/1566201/files/978-3-319-00327-6_BookBackMatter.pdf](https://cds.cern.ch/record/1566201/files/978-3-319-00327-6_BookBackMatter.pdf)
[4] <NAME>, <NAME>,\textit{Limit Distributions for Sums of Independent Random Variables}, (Addison-Wesley, Reading, 1954)
<file_sep>/README.md
## tekeh.github.io
<file_sep>/teaching.md
---
layout: page
title: Teaching
---
<b>Supervisions</b>
<ul>
<li><a href="">Part IA NST: Mathematical Methods for Natural Sciences</a></li>
<li><a href="">Part IA NST: Physics </a></li>
<li><a href="">Part II MATH: Statistical Physics </a></li>
</ul>
<b>Examples Classes</b>
<ul>
<li><a href="">Part II NST: Theories of Quantum Matter</a></li>
</ul>
<file_sep>/_posts/2020-11-21-monge-ampere.md
---
layout: post
title: Partition Function Level Sets
image: /img/hello_world.jpeg
tags: []
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Suppose I want to find a $$\beta$$ which satisfies the following sort of equation:
$$
k = \int e^{\beta h(\boldsymbol{\alpha})} d \boldsymbol{\alpha}
$$
where $$k >0$$ is a constant and $$h$$ is a known real function of the parameters $$\boldsymbol{\alpha} \in \mathbb{R}^n$$. How might I do so? Here we present one possible approximate route, and briefly analyse the resulting equation. If the exponent has a suitably steep minima which we can expand around, then we might try a saddle point approximation
$$
\begin{equation}
\begin{aligned}
k &= e^{\beta h({\boldsymbol{\alpha}*)}} \int e^{(\alpha - \alpha*)_i(\alpha - \alpha*)_j \frac{\partial^2 \beta h}{\partial \alpha_i \partial \alpha_j} } d \boldsymbol{\alpha} \\
&\approx e^{\beta h({\boldsymbol{\alpha}*)}} \Big(\frac{(2\pi)^n}{det \frac{\partial^2 \beta h}{\partial\alpha_i \partial\alpha_j} } \Big)^{1/2} \\
\end{aligned}
\end{equation}
$$
Upon rearranging
$$
\begin{equation} \label{eq:monge-ampere} \tag{1}
\implies det \frac{\partial^2 \beta h}{\partial\alpha_i \partial\alpha_j} \vert_{\boldsymbol{\alpha = \alpha*}} = \frac{1}{k^2} e^{2 \beta h({\boldsymbol{\alpha}*)}} (2 \pi)^n
\end{equation}
$$
This is similar to a nonlinear PDE called the **Monge-Ampere Equation**, which has uses in diffeential geometry and optimal transport (apparently). The similarity is superficial - remember $$h$$ is known, and the expressions hold at a minima.
$$\beta$$ is the solution to the non-linear algebraic equation which now involves no integrals. It still involves a determinant of the hessian, so it would be interesting to see if we could simplify this expression. This _could_ be simplified exactly in a number of special cases. Some of the resulting equations for $$\beta$$ are nonsensical, and thus betray the crassness of the saddle point approximation. We list some cases below.
#### $$h = h(\boldsymbol{c \cdot \alpha})$$ (const $$\boldsymbol{c}$$)
In this case the LHS becomes
\begin{equation}
\begin{aligned}
det \frac{\partial^2 h}{\partial\alpha_i \partial\alpha_j} &= det(c_i c_j h'') = 0 \\
\end{aligned}
\end{equation}
where the last equality comes from the fact that the tensor is of rank 1. Clearly Eq \eqref{eq:monge-ampere} makes little sense and therefore [another approach is needed]().
#### $$h =h(\vert \boldsymbol{\alpha}\vert)$$ (rotational symmetry)
Denote $$ \vert \boldsymbol{\alpha}\vert = \alpha$$. In this case the LHS becomes
$$
\begin{equation}
\begin{aligned}
det \frac{\partial^2 h}{\partial\alpha_i \partial\alpha_j} &= det\Big[ \delta_{ij} \frac{h'}{\alpha} + \alpha_i \alpha_j \big( \frac{h''}{\alpha^2} - \frac{h'}{\alpha^3} \big) \Big] \\
&= \Big( \frac{h'}{\alpha} \Big)^{n-1} h'' = \frac{1}{n\alpha} \big((h')^n \big)'
\end{aligned}
\end{equation}
$$
The last line comes from considering the product of eigenvalues of the derived second rank tensor.
**[References]**
<file_sep>/_posts/2019-02-13-topics.md
---
layout: post
title: topic ideas
image:
tags: []
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Roughly in order of interest. There are other things of interest but these are just possible projects/vague directions i could identify
<h2> Upper Critical Dimension (UCD) for Mean Field Rheological Models </h2>

<b>Background</b>
- <NAME> and Wyart published <a href="https://journals.aps.org/prx/pdf/10.1103/PhysRevX.6.011005"> Mean Field Description of Plastic Flow in Amorphous Solids </a>, where they calculated an exponent $$\theta $$ that characterises the density of regions that flow plastically under small shear stress ( $$ P(x) \approx x^{\theta} ) $$. They calculate the exponent by using a broadly distributed noise term corresponding to the statistics of Levy flights. Their $$\theta$$ starts to agree well with simulation for $$d=4$$ (and greater, I assume) which is weak evidencefor it being the lower critical dimension $$d_c$$. They mention that they no Ginzburg-like argument is known for why $$d=4$$ is relevant.
- Model: discrete sites with stress values with rules for redistribution. $$x_j \equiv 1 - \sigma_i$$ where $$\sigma_i$$ is the stress on site $$i$$. Update rules are:
$$
x_i(l+1) = 1 \\
x_j(l+1) - x_j(l) = - \frac{1 - x_i(l)}{N-1} + \underbrace{\zeta_i}_{\text{broadly distributed}}
$$
<b> Directions </b>
- Development of Ginzburg argument. Criterion typically derived by considering fluctuations about the mean field bahviour starting from a free energy, but no free energy here. Effective one such as from a LD principle? Gaussian mixture modelling of the noise to replicate broad tail? Something analogous to <a href="https://arxiv.org/pdf/1803.09525.pdf">dynamical RG</a>? if possible dimensional expansions for exponents when $$d < d_c$$. Could possibly link to other MF glass/rheological models (such as <a href="https://journals.aps.org/prl/pdf/10.1103/PhysRevLett.81.2934"> HL-model </a> or <a href="">Zamponi's</a> infinte dimensional glasses, where there are also no Ginzburg like arguments or dimensional expansions)
<h2> Memory and Resets with Large Deviations </h2>

<b> Background </b>
- There is a lot of unconnected work to do with memory effects in various stochastic systems. The most comprehensive work I've seen is by <NAME> in <a href=" https://fys.kuleuven.be/itf/staff/christ/files/pdf/pub/gleresponsefinal.pdf "> Fluctuation-response relations for Nonequilibrium Diffusions with Memory </a> where they consider linear underdamped langevin equations with a memory kernel on the velocity damping term. In addition there has been some work to do with breaking detailed balance <a href="http://www.msc.univ-paris-diderot.fr/~vanwijland/PRE-98-062610-2018.pdf">without introducing memory</a> (Fodor, Hayakawa, Tallier, Wijland)
- <a href="https://iopscience.iop.org/article/10.1088/1751-8121/aa5734/meta">Harris and Touchette</a> studied how discrete time stochastic resetting can lead to dynamical phase transitions (of both orders). They looked at particular model with uniform resets, but have left out the continuum case, space-time dependent resetting rates etc and mention this as an interesting future direction
<b> Directions </b>
- Calculation of large deviation behaviour of space-time dependent resets for brownian particles. There is already a recent <a href="https://journals.aps.org/pre/abstract/10.1103/PhysRevE.96.022130">path integral formalism</a> to deal with space dependent resets, so it may be relatively straightforward to apply large deviation biases analytically as well as computationally determine qualitative features of Large devitaion transitions in such systems. For a particle moving in a 1D potential $$V(x)$$ and with a spatially varying reset rate $r(x)$ the probability of no reset is
$$
P_{\text{no reset}}(x, t) = \int \mathcal{D} x(t) \exp(-S_{\text{res}}[x(t)]) \\
\text{with} \\
S_{\text{res}} = \int^t_0 dt \Bigg[ \frac{ [(dx/dt) - \mu F ]^2 }{4D} + \frac{\mu F'}{2} + r(x) \Bigg]
$$
And biased probability distributions take the form $$ P_{bias} \propto e^{-\lambda A} P_{\text{n_reset}}$$. Would reduce to a hermitian quantum problem (as in the <a href="https://arxiv.org/pdf/1808.06986.pdf">Touchette paper</a> ) and may be able to say something about optimalling resetting choice for some defined escape times, confinement etc etc
<h2> "Odd Elasticity" </h2>

<b> Background </b>
- <NAME> has done preliminary work on the mechanics of elastic materials which exhibit "odd elasticity". This means that the tensor relatin stress and strain via $$ \sigma_{ij} = K_{ijmn} \epsilon_{mn} $$ is not even under the reversal of the first two and second two indices, but is in fact odd i.e $$ K_{ijmn} = - K_{mnij} $$. This difference to the normal symmetry can be related to active units within the materials in question, which are being experimentally realised. To my understanding, the elastic theory of such materials has basically never been studied.
<b> Directions </b>
- Work extraction properties of these elastic materials (although VV has some unpublished work on this in progress)
- Elastic wave propogation, stability analyses, dislocations, thermal properties i.e all the basic analysis but for systems with this new symmetry
<file_sep>/_posts/2021-03-05-funky-symplectics.md
---
layout: post
title: Funky Symplectics
image: /img/hello_world.jpeg
tags: []
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Hamiltonian mechanics occurs on a symplectic manifold, but what does that mean? Well, it means that the manifold created by the coordinate variables is equipped with a **differential two-form**. Let's zoom in on this.
The canonical coordinates for a mechanical system are denoted by $${\bf \xi} = (q_i, p_i)$$ where $$q_i$$ are the _generalised coordinates_ and $$p_i$$ are their associated _conjugate momenta_. The equations of motion are given by _Hamilton's equations_.
$$
\dot{p_i} = - \frac{\partial \mathcal{H}}{\partial q_i}
$$
$$
\dot{q_i} = \frac{\partial \mathcal{H}}{\partial p_i}
$$
A function $$f = f(q_i,p_i)$$ has a time derivative given in terms of the _poisson bracket_:
$$
\frac{df}{dt} = \frac{\partial f}{\partial t} + \{f, \mathcal{H}\}
$$
where $$\{f, g \} = \sum_{i=1}^n \Big( \frac{\partial f}{\partial q_i} \frac{\partial g}{\partial p_i} - \frac{\partial f}{\partial q_i} \frac{\partial g}{\partial p_i} \Big)$$.
Liouvelle's theorem falls out of the Hamiltonian formulation, and tells us that the phase space evolves as an incompressible fluid. Another way of saying this is that the volume element $$dV = \prod_{i=1}^N dq_i dp_i$$ will be of constant magnitude, even if the shape distorts during the flow.
All of these equations and results can be recast into the language of differential geometry.
Our manifold $$\mathcal{M}$$ is of dimension $$2n$$, the coordinates being $$ {\bf \xi} = (q_i, p_i)_{i=1..n}$$. Our hope is to describe the time evolution of our coordinates as a flow on this manifold. To do this we need to connect different points of the manifold to one another, so calculus seems necessary. And in differential geometry this is handled using differential forms.
Define a two form by (Einstein summation assumed from here)
$$
\omega = \frac{1}{2} \tilde \omega_{\alpha \beta} d\xi^{\alpha} \wedge d\xi^{\beta}
$$
and a velocity vector field using our canonical coordinates by
$$
v = \xi_{\alpha} \frac{\partial}{\partial \xi_{\alpha}} = \dot q_i \frac{\partial}{\partial q_i} + \dot p_i \frac{\partial}{\partial p_i}
$$
Then the hamiltonian flow can be written by
$$ \label{eq:differential-hamiltonian-flow} \tag{1}
dH = - \omega(v, )
$$
when $$\omega$$ is in _Darboux form_ $$ dp^1 \wedge dq^1 + dp^2 \wedge dq^2 + ... dp^n \wedge dq^n$$ then we get exactly Hamiltons equations above. The symplectic matrix $$\tilde \omega$$ can be written in block form as below.
$$
\tilde \omega = \begin{pmatrix}
{\bf 0} & {\bf I} \\
-{\bf I} & {\bf 0} \\
\end{pmatrix}
$$
Within differential geometry there exists a natural volume element, derived from the symplectic form $$\omega^n/n! = \sqrt{\det(\tilde\omega)} \bigwedge_{i=1}^n dp^i \wedge dq^i $$. This volume form (which describes a volume in phase space) is _invariant_. This is a recasting of Liouvelle's theorem, which says that phase space volumes are incompressible and evolve analogously to an incompressible fluid.
All of the above is a recasting of the Hamiltoniain framework. However, not that we have this recasting we can imagine how it can be extended naturally. Hamilton's equations of motion are great, and they can describe a great many systems, but their form is restrictive. It is impossible to represent certain types of forces in the vanilla framework. This is fine - in such cases we would typicaly work on the level of the equations of motion without any cosideration of a Hamiltonian or symplectic manifold. But the Hamiltonian formalism is quite a nice tool, and there are strong theorems attached to it (Liouvelle). As well as that there exists great tools for analysing symmetry within it (Noether, or whatever is to Hamiltonians what Noether is to Lagrangians). So maybe there is a way to use Hamiltonians in more peculiar situations?
Let us consider on augmentation - we could imagine a more general symplectic matrix. The idea would be that changing $$\omega$$ would allow Eq \ref{eq:differential-hamiltonian-flow} to express more general dynamical equations. As long as we can pick an appropriate $$H$$ and $$\omega$$, we can still use the power of Hamiltonian dynamics. Therefore, consider
$$
\hat \omega = \begin{pmatrix}
{\bf \Omega}^{(q)} & {\bf S} \\
-{\bf S}^T & {\bf \Omega}^{(p)} \\
\end{pmatrix}
$$
Then the two form can be written
$$
\omega = S_{\alpha\beta} dp^{\alpha} \wedge dq^{\beta} + \Omega^{(q)}_{\alpha\beta} dq^{\alpha} \wedge dq^{\beta} + \Omega^{(p)}_{\alpha\beta} dp^{\alpha} \wedge dp^{\beta}
$$
The natural volume is probably useful to know. In this case it is merely
$$
\det(\hat\omega) = \det({\bf \Omega}^{(q)} {\bf \Omega}^{(p)} + {\bf S}^T {\bf S } )
$$
Cool.
This will be applied to something in the future.
**[References]**
[https://arxiv.org/pdf/cond-mat/0506051.pdf](https://arxiv.org/pdf/cond-mat/0506051.pdf)
[//]: # Now for an application - an underdamped system in 1-dim obeys the following ODE
[//]: #
[//]: # $$
[//]: # m \ddot{r} = - \gamma \dot{r} + F(r)
[//]: # $$
[//]: #
[//]: # First we need to appreicate that for $$\gamma \neq 0$$, this equation has no Hamiltonian in the vanilla sense. (Think about the evolution of a phase space element for $$F=0$$. It's collapse to a line on $$p=0$$ shows that phase volume is not conserved)
[//]: #
[//]: # $$
[//]: # \mathcal{L} = m(\dotr)^2/2
[//]: # $$
[//]: #
[//]: # which can be rewritten in terms of two 1st order SDEs
[//]: #
[//]: # $$
[//]: # \dot{r} = \frac{\partial E(p)}{\partial p} = p/m
[//]: # $$
[//]: #
[//]: # $$
[//]: # \dot{p} = - \gamma p - \frac{\partial V(r)}{\partial r}
[//]: # $$
[//]: #
[//]: # The second version makes the connection to the dynamical Hamiltonian formalism more explicit. Consider Hamiltons equations in phase space
<file_sep>/_posts/2021-03-05-simple-questions-glass.md
---
layout: post
title: Simple Questions about Difficult Topics (Glasses - in progress)
image: /img/hello_world.jpeg
tags: []
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
It is hard to navigate a complex field with tons of literature, to both learn about the previous investigations and note where the gaps are. It is also hard to ask good questions that will yield fruitful discussions. So instead I will ask bad questions, and hope something useful is stumbled upon.
**What is a glass?**
A glass is an amorphous material that can behaves in a glassy way. This is characterised by mechanical rigidity despite no long range crystalline order (in fact, the spatial disorder is similar to that of a liquid). They can be characterised by an extremely long relaxation time (extremely high viscosity).
**What is the glass transition?**
The glass transition is the transition from a non-glassy (liquid) state to a glassy state. This is often achieved by performing a fast quench from high temperatures to low - it must be fast to avoid the crystalline phase. The crossover happens at the experimentally defined "glass temperature" $$T_g$$, which is roughly the temperature at which the viscoity is "quite large". The idea is that past this temperature, any evolution happens at timescales not accessible to experiment. This temperature is protocol dependent.
**Does the relaxation time increase different than what you would expect considering activation energy (Arrhenius hopping) arguments?**
Yes.
Not all glasses follow an appropriate Arrhenius law
$$
\tau = \tau_{\infty} \exp\Big( E_{\rm eff}/T\Big)
$$
Those which do for an appreciable range of temperature are called _strong glass formers_, but even those have an $$E_{\rm eff}$$ which increases as temperature decreases ('super-Arrhenius').
**So the glass transition is not actually thermodynamic?**
Debatable. Although the transition is not sharp, and glasses are often characterised by their dynamical slow-down, there are some who think there is a hidden thermodynamic transition at play. Perhaps in some thermodynamics theory the relaxation time _does_ formally diverge at some finite temperature.
**What is the evidence that the glass transition is thermodynamic?**
**1**, Suppose we fit the relaxation time assuming there is a finite temperature divergence at $$T_0$$ (VFT law)
$$
\tau = \tau_0 \exp\Big( DT_0/(T - T_0)\Big)
$$
Now suppose we calculate the _excess entropy_ of a liquid compared to the solid phase. If we plot $$\mathcal{S}_{\rm exc}$$ vs $$T$$, and extend the the line past the glass transition temperature, this excess entropy vanishes at some $$T_K$$ (Kauzmann temperature) $$\approx T_0$$. The correlation isn't perfect, there can be differences of up to 20%, but they are a lot closer a lot of the time. So there seems to be some link between thermodynamics ($$T_k$$) and dynamics $$T_0$$.
**2** The specific heat is (nearly) discontinuous at $$T_K$$
**But what is the thermodynamic order parameter?**
Unknown!
To date there haven't been any static order parameters which change appreciably at a finite temperature which would correspond to the glass transition. Below we list a large collection of ones which have been studied and reported in literature:
-
-
-
**Is there a diverging static lengthscale, as is typical in thermodynamic transitions?**
tbf
**So there isn't any good order parameter?**
That is a different question, _dynamic_ order parameters can act as signatures of the transition. For example, the intermediate scattering function
$$
F({\bf q}, t) = N^{-1} \langle \rho_{\bf q}(t) \rho_{\bf -q}(0) \rangle
$$
although other dynamical probes are possible, such as the dielectric susceptibility.
**What is the mode coupling temperature?**
The temperature below which the free energy landscape fragments inty many local minima corresponding to metastable amorphous states. Above $$T_{\rm MCT}$$ there is a single minimum in the free energy. Many theories predict that the free energy s analytic at this temperature (and people seem to take this as strong evidence that it is indeed true for real systems).
**WHat is dynamical facilitation?**
Dynamic facilitation is the process whereby relaxation of a local region in a glassy system enables another local region to subsequently move and relax. This facilitation can be long ranged at low temperatures, but people debate why.
_This is constantly updated. Last edit: 050321_
**[References]**
https://arxiv.org/pdf/1011.2578.pdf
<file_sep>/_posts/2019-03-22-thermal-beads.md
---
layout: post
title: Thermal Beads
image: /img/hello_world.jpeg
tags: [stochastic processes, thermodynamics]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
A simple calculation to help me understand something larger. Suppose there are two beads in between two parallel walls which can move in one dimension perpendicular to the plane of the walls. They are connected together by elastic spring with strength $$k_{12}$$, and each is further connected to the wall initially closest to them by springs of constant $$k_1 $$ and $$k_2$$ respectiviely. They are both held at different temperatures $$T_1$$ and $$T_2$$, again respectively. Withiin the framework of stochastic differential equations we can write
$$
\begin{equation}
\begin{aligned}
\dot x_1 &= k_{12} \mu (x_2 - x_1) - k_1\mu x_1 + \sqrt{2 T_1} \eta_1 \\
\dot x_2 &= k_{12} \mu (x_1 - x_2) - k_2\mu x_2 + \sqrt{2 T_2} \eta_2
\end{aligned}
\end{equation}
$$
or in a vector form
$$
{\bf \dot x} = - {\bf \hat K} {\bf x} + {\bf \hat B} {\bf \eta} \\
\text{with} \\
{\bf \hat K} = \mu \pmatrix{ (k_1 + k_{12}) & -k_{12} \\ -k_{12} & (k_{12} + k_2) } \label{eqn:k-mat} \tag{1}\\
{\bf \hat B} = \pmatrix{ \sqrt{2T_1 } & 0 \\ 0 & \sqrt{2T_2 } }
$$
By rotating this equation we can decouple the problem into two independent normal modes subject to brownian motion
$$
{\bf \dot u} = - {\bf \hat \Lambda} {\bf u} + (2 {\bf \hat D})^{1/2} {\bf \eta} \\
\text{with}\\
{\bf \hat \Lambda} = \mu \pmatrix{ \lambda_1 & 0 \\ 0 & \lambda_2 } \\
(\bf{ \hat D})^{1/2} = \pmatrix{ \sqrt{T_1 \cos^2 \phi + T_2 \sin^2 \phi } & 0 \\ 0 & \sqrt{T_1 \sin^2 \phi + T_2 \cos^2 \phi } }
$$
With $$\tan \phi = \frac{k_1 - k_2}{k_{12}} \Big[ \sqrt{1 + (\frac{k_{12}}{k_1 - k_2})^2 } - 1 \Big] $$. Each normal mode experiences some modified noise, but Tr( $${\bf D}$$ ), which can be related to the total power in the harmonic modes, is conserved. Since each mode is an independent brownian process, the steady state solutions can then be written explicitely as the product of two Boltzmann weights in the normal coordinates. Once roated back we get that the steady state distribution is a quadratic form in the original coordinates.
$$
\mathcal{P}_{ss}(x) = \frac{1}{\sqrt{ (2 \pi)^2 \text{det} {\bf \hat C} }}\exp \Big( - \frac{1}{2} {\bf x}^T {\bf \hat C}^{-1} {\bf x} \Big) \tag{2} \label{eqn:prob-ss}
$$
where $$\bf{ C} = \langle \bf{x} \otimes \bf{x} \rangle $$ is the covariance matrix which satisfies the <b> Lyaponov equation </b>
$$ {\bf K C + C K^{T}} = 2{\bf D} \tag{3} \label{eqn:lyaponuv} $$.
Usually some algorithm is implemented to solve the equation in the general case such as the <b> Bartels-Stewart algorithm </b> (suitable for sparse $${\bf K}$$ and low-rank $${\bf D} $$ ), but for our 2x2 matrices we can just solve elementwise. It was shown that this steady state equation will produce a phase space flux unless the covariance matrix is a multiple of $$\bf K^{-1}$$.
For reference, the associated Fokker-Plank equation can be written
$$
\partial_t \mathcal{P}(\bf{x}, t) = \nabla \cdot \Big[ \bf{ D} \nabla \mathcal{P} - \bf{ \hat K} \bf{ x} \mathcal{P} \Big] \equiv \nabla \cdot {\bf J}
$$
To work out the thermodynamics we need to first calculate the quasistatic energy in terms of the parameters of the system (in this case the spring constants $$k_1, k_2, k_{12}$$).
$$
\begin{equation}
\begin{aligned}
\langle V \rangle &= \frac{1}{2} \langle \bf{x}^T \bf{ \hat K} \bf{ x} \rangle = \frac{1}{2} K_{ij} \langle x_i x_j \rangle = \frac{1}{2} \text{Tr} \big( K C \big) = \frac{1}{2} \text{Tr}\big( D \big) \\
\langle V \rangle &= \frac{1}{2} (T_1 + T_2)
\end{aligned}
\end{equation}
$$
As we should expect from equipartition with respect to the normal modes.
$$ \langle \mathcal{W} \rangle = \langle \partial_{\alpha_i} V \rangle d \alpha_i$$ where $$\alpha_i$$ are the controllable parameters of the system. In this case they would be the strength of the springs attached to the masses. We can see that $$ \langle \partial_{\alpha} V \rangle = \frac{1}{2} \partial_{\alpha} K_{ij} \langle x_i x_j \rangle = \frac{1}{2} C_{ij} \partial_{\alpha} K_{ij} $$. The term would be a total derivative under the condition stated before for zero phase space flux (i.e $$ C \propto K^{-1}$$) but in general it will not be, and we will thus get work out when undergoing cyclic protocols. Let us take the simplest case where we change $$k_1$$ and $$k_2$$ in tandem, keeping the spring connecting the two masses unchanged. The relevant part of the infintesimal work is
$$
\langle d \mathcal{W} \rangle = \frac{1}{2} C_{11} dk_1 + \frac{1}{2} C_{22} dk_2
$$
Is this an exact differential? If it is then all loop integrals vanish. We can check to see whether there is a consistent potential function geneerating this one-form (i.e look for $$f$$ s.t $$ df = \langle d \mathcal{W} \rangle $$). Integrating the first term using the expression for $$ \bf{\hat C}$$ appearing in [Eq S4 in <NAME>, <NAME>, and <NAME>'s paper]( https://arxiv.org/pdf/1809.04639.pdf )
$$
\frac{1}{2} \int C_{11} dk_1 = T_1 \ln \big[ (k_1 + k_{12}) (k_2 + k_{12}) - k^2_{12} \big] + \\
\frac{( T_2 - T_1) k^2_{12} }{ (k_2 + k_{12})^2 + k_{12}^2 } \Big( \ln \bigg[ \frac{k_1 + k_2 + 2 k_{12}}{ (k_1 + k_{12})(k_2 + k_{12}) - k_{12}^2 } \bigg] + \ln \big[ k_2 + k_{12} \big] \Big) + A(k_2, k_{12}) \tag{4} \label{eqn:potential}
$$
$$\frac{1}{2}\int C_{22} d k_2 $$ should be the same expression as Eq \ref{eqn:potential} under swapping $$ T_1 \rightarrow T_2, k_1 \rightarrow k_2 $$ and $$ k_2 \rightarrow k_1$$ by symmetry (of course with a new arbitrary function $$A'(k_1, k_{12})$$). This shows there is no potential function which can generate this one-form, and so we can have non-zero work flux when $$T_1 \neq T_2$$. We can form a heat engine when there is something like a temperature gradient (surprise surprise /s).
Another way to see this condition is in terms of the stady state profile being only a function of the Potential and no other details i.e $$\rho = \rho(V)$$ alone. Clearly, unless $$\bf{ \hat C} \propto \bf{ \hat K}^{-1} $$ this is not the case for the quadratic form in Eq \ref{eqn:prob-ss}.
References:
{1} [ Non-equilibrium dynamics of isostatic spring networks ](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.121.038002)
<file_sep>/_posts/2019-02-21-rheology-levy.md
---
layout: post
title: Rheology with Levy Flights
image:
tags: [statistical physics, rheology, paper summary]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
<h2> Premise </h2>
I recently came across a <a href="https:/fill.in.later.com">paper</a> which investigates rheological properties of a material using a stochastic Levy flight process. To construct this mean field theory, it first starts by considering discretised space, with each cell/block/site $$i$$ taking some local stress value $$\sigma_i$$. As the elastic system undergoes relaxation, or local changes of arrangement this stress field over space will vary. These sites all interact - if one site undergoes a massive change in stress then it will effect the stress felt in other sites in a local manner.
<h2> Model </h2>
One route to modelling how the relaxation of one site $$i$$ affects the stress field at site $$j$$ is through the <b> Eshelby kernel </b>:
$$
\sigma_j = \mathcal{G}_{ij}( r_i - r_j ) \sigma_i \tag{1} \label{eqn:eshelby}
$$
This form is well motivated from the theory of linear elasticity. The stress field at different points should be related via a propagator (Green's function), and although there is no reason to expect amorphous solids should follow these rules in full generality, this form works quite well for them too.
This propogator takes different forms depending on the dimension $$d$$ and goes like $$\sim 1/r_{ij}^d $$. Now imagine a more dynamic situation, where site stresses are constantly changing, sometimes in a continutous fashion (due to something like elastic deformations) or in sharp discontinous ways (due to relaxation events). The combination of all of these changes in stress is a source of <i> mechanical noise </i> for the site. Although we may be tempted to use some sort of central limit argument to model this noise as Gaussian, Eq \ref{eqn:eshelby} tells us that perhaps the noise follows a different distribution. In particular, if we imagine that the small elastic deformations which change stresses at <i>other </i> sites to be of the same order, then the noise felt at site $$i$$ should be power law, which is more broadly distributed than a Gaussian distribution. On top of this, because the sites are discretised the random mechanical noise should have some finite cut off, related to the size of each site and magnitude of average changes in stress.
So now we should write down an equation for the dynamics. A constant shear stress $$\Sigma = \sum_i \sigma_i/N$$ is applied to system. Let us describe the relaxation behaviour by saying if any site's stress $$\vert \sigma_i \vert > 1$$ then it is classed as "unstable", and after a constant time will relax to zero. Defining $$x_i \equiv 1 - \sigma_i$$ we can write down how stress is redistributed in the system after a plastic event
$$
x_j(l+1) - x_j(l) = \mathcal{G}_{ij}(r_i - r_j) \sigma_i(l) \tag{2} \label{eqn:model}
$$
The variable $$l$$ is an integer numbering the number of plastic events that have occured. Now we pass over into a mean field model, where we say that each site is interacting in an identical fashion. We relax an unstable site completely, and redistribute its stress throughtout the systems $$ N-1 $$ remaining sites evenly but with broad fluctuations on top. In this way we completely ignore any spatial information in the system.
$$
x_i(l+1) = 1 \\
x_j(l + 1) - x_j(l) = - \frac{1 - x_i(l)}{N - 1} + \zeta_j
$$
Where $$\zeta$$ is our broad noise (with zero mean). It takes values according to the distribution
$$
p(\zeta) = \frac{A}{N} \vert \zeta \vert^{-1-\mu}
$$
with a lower cut off at $$ \zeta_c = (2A/\mu)^{1/\mu} N ^{-1/\mu} $$. When $$\mathcal{G} \sim 1/r^{\alpha}$$ then $$\mu = d/\alpha$$, so we are mostly interested in the physical case of $$\mu=1$$.
We can then finally pass to a continuous description of this system by letting $$N \rightarrow \infty$$ whilst keeping $$ \gamma \equiv l/N$$ a constant.
$$
x_j(\gamma) = x_j(0) - v \gamma + \tilde \zeta_j(\gamma) \tag{3} \label{eqn:levy-flight}
$$
where the drift $$v$$ is the mean stress of unstable sites before relaxation i.e $$v = \langle \sigma_u \rangle$$ in the paper's notation. If $$\Sigma > 0$$ then clearly $$ v > 0 $$ as well. The noise term is now an accumulation of $$\gamma N $$ random kicks and we call it's distribution (which is convolutional) $$ p_{\gamma}(\zeta)$$. Using a standard sort of Markovian argument we can then derive a Fokker Plank master equation for the dynamics.
$$
\frac{\partial P}{\partial \gamma} = v \frac{\partial P}{\partial x} + \int^{\infty}_{\infty} [ P(y) - P(x)] w'(y - x) dy + \delta(x-1) \\
\text{with} \\
w'(x) = \lim_{\gamma \rightarrow 0} \frac{w_{\gamma}(x)}{\gamma}
$$
Lin and Wyart then analyse the Fokker Plank equation for various $$\mu$$, looking for stationary solutions of the form $$ P(x) \sim P_0 + C_0 x^{n} $$ for $$x \ll 1$$. From this they can deduce the psedogap exponent.
<h2> Main Results </h2>
The main results of the paper are as follows:
- for $$\mu = 1$$ (the most physically relevant case, and corresponds to Levy flights) the pseudogap exponent $$\theta$$ for critically sheared systems is not universal, and depends on the sytem specifics.
- There is a violation of the <b>marginal stability hypothesis</b>
- $$\theta$$ varies non-monotonically with stress, a result which was previously unexplained (even qualitatively)
<h2> Other Considerations </h2>
Perhaps the most interesting open question from the problem is the role of spatial dimension. One thing Lin and Wyart oobserve is that their mean field predictions get better as the dimension increases, which they mark as evidence that their mean field model is correct.

To get this behaviour they need to somehow extract $$\theta$$ for finite dimensional systems. They do this by simulating according to Eq \ref{eqn:model} with a shuffled Eshelby kernel. To determine $$\theta$$, they simulate the system with the kernel undergoing a random reshuffling after each event, and measure $$P(x)$$ nclose to 0. To comput predictions they need the ratio $$A/v$$ which ends up being equivalent to determining $$A_0$$, the amplitude of the power law distrobution of the Eshelby kernel (which you can derive by looking at the max value of $$\mathcal{P}(\mathcal{G})$$).
Possible calculation routes to follow.
<file_sep>/_posts/2019-07-28-angular-averaged.md
---
layout: post
title: Integrals over Solid Angles
image: /img/hello_world.jpeg
tags: [statistics]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Oftentimes we must do some form of average to calculate an expected quantity. In this post we'll consider doing angular averages of scalar functions of vectors in various dimensions. We'll first consider integrals of the form
$$
\langle f( {\bf{a_1}}, {\bf{ a_2}}, .., {\bf{ n}}) \rangle = \int f( {\bf{a_1}}, {\bf{ a_2}}, .., {\bf{ n}}) \frac{d \Omega_n}{2 \pi}
$$
where the integration domain is over all directions the unit vector $$\bf{n}$$ can take. These integrals can occur during perturbative calculations for non-equilibrium field theories, for example. Let's first consider a subset of expressions - $$f_{\Pi_n} = (\bf{a_1} \cdot \bf{n}) (\bf{a_2} \cdot \bf{n})...(\bf{a_n} \cdot \bf{n})$$. How might we perform such an average? Note that using the summation convention we can write this expression as
$$
\langle f_{\Pi_m}({\bf a}_i) \rangle = (a_1)_{i_1} (a_2)_{i_2}...(a_m)_{i_m} \int n_{i_1} n_{i_2} ... n_{i_m} \frac{d \Omega_n}{2 \pi}
$$
The integrand is now a tensorial quantity. The integral should be invariant under rotations of the unit vector in the integrand as we integrate over all angles. As the integral is a tensor invariant under rotation transformations it will be isotropic, and we can therefore restrict the form to
$$
\int n_{i_1} n_{i_2} ... n_{i_m} \frac{d \Omega_n}{2 \pi} = \mathcal{A}_m I_{i_1 i_2 ... i_m}
$$
where $$I_{i_1, i_2, ...,i_m}$$ is the general isotropic tensor. It should be symmetric under the exchange of any two indices, (this means the tensor is identically 0 for an odd number of vectors, as the isotropic tensor of odd rank must involve the totally antisymmetric tensor). In even dimension we can write $$I$$ as a sum of the products of kronecker delta's, with all possible pairings.
The first 2 non-zero tensors of this type are
$$
\begin{equation}
\int n_i n_j \frac{d \Omega_n}{2 \pi} = \mathcal{A}_2 \delta_{ij} \\
\int n_i n_j n_k n_l \frac{d \Omega_n}{2 \pi} = \mathcal{A}_4 ( \delta_{ij} \delta_{kl} + \delta_{ik} \delta_{jl} + \delta_{il} \delta_{jk} ) \\
...
\end{equation}
$$
To evaluate the coefficients is fairly easy, we merely choose any easy to calculate component. For example we can choose all indices $$= 1$$.
$$
\begin{equation}
\begin{aligned}
\int n_{1} n_{1} ...n_{1} n_{1} \frac{d \Omega_n}{2 \pi} &= \mathcal{A}_{2m} \frac{(2m)!}{2^m m!} \\
&= \int ( \cos \theta)^{2m} \frac{d\theta}{2\pi} \\
\implies \mathcal{A}_{2m} = \frac{1}{2^m m!} \\
\end{aligned}
\end{equation}
$$
Now we can evaluate $$f_{\Pi_{2m}}$$.
$$
\begin{equation}
\begin{aligned}
\langle f_{\Pi_n}({ {\bf a}_i} ) \rangle &= \int f( {\bf{a_1}}, {\bf{ a_2}}, .., {\bf{ n}}) \frac{d \Omega_n}{2 \pi} \\
&= \mathcal{A}_{2m} \times ( \text{sum of all possible dot product pairs}) \\
\end{aligned}
\end{equation}
$$
Consider another integral
$$
\begin{equation}
\begin{aligned}
\langle e^{\bf{ c \cdot n}} \rangle &= \int e^{\bf{c} \cdot \bf{n}} \frac{d \Omega_n}{2 \pi} \\
\end{aligned}
\end{equation}
$$
This can also be done in a systematic way by taylor expanding the integrand $$( c = \vert {\bf c} \vert)$$.
$$
\begin{equation}
\begin{aligned}
\langle e^{\bf{ c \cdot n}} \rangle &= \sum_k \frac{1}{k!} f_{\Pi_k} \\
&= \sum_{l=0} \frac{1}{(2l)!} \frac{1}{2^{k+1}} \begin{pmatrix} k \\ k/2 \end{pmatrix} (c^2)^k \\
&= \frac{1}{2} \sum_{l = 0}^{\infty} \frac{1}{(l!)^2} (c/2) ^{2l} = I_0( c ) \\
\end{aligned}
\end{equation}
$$
where $$I_0(x)$$ is the zeroth order modified bessel function of the first kind.
But there are more general tricks we can play. Notice that since these integrals are done over solid angles, the final answer must depend on the magnitude of the vectors (and dot products between them if there is more than one unique vector involved). Let us examine $$ \langle e^{\bf{ c \cdot n}} \rangle $$, and this time take a vector derivative.
$$
\begin{equation}
\begin{aligned}
\nabla_{\bf c} \langle e^{\bf{ c \cdot n}} \rangle &= \int {\bf n} e^{\bf{c} \cdot \bf{n}} \frac{d\Omega_{\bf n}}{2 \pi}\\
\nabla_{\bf c} \cdot \nabla_{\bf c} \langle e^{\bf{ c \cdot n}} \rangle &= \int n^2 e^{\bf{c} \cdot \bf{n}} \frac{d\Omega_{\bf n}}{2 \pi} = \langle e^{\bf{ c \cdot n}} \rangle \\
\end{aligned}
\end{equation}
$$
since $$\langle e^{\bf{ c \cdot n}} \rangle $$ can only depend on the magnitude of the vector $$\bf c$$, $$ \nabla_{\bf c} \cdot \nabla_{\bf c} $$ must be the radial part of the laplacian in $$d = 2$$.
$$
\begin{equation}
c^{-1} \partial_c \Big( c \partial_{c} \Big( \langle e^{\bf{ c \cdot n}} \rangle \Big) \Big) = \langle e^{\bf{ c \cdot n}} \rangle
\end{equation}
$$
Solving the equation with the boundary conditions at $$c = 0, \infty$$ again gives us $$I_0( c )$$.
The advantage of this sort of reasoning compared to the more direct method is that it is clear how it generalises to other dimensions - just replace with the radial part of the laplacian with appropriate dimension. For example in $$d = 3$$ the angular integral can be seen to be
$$
\begin{equation}
\langle e^{\bf{ c \cdot n}} \rangle = \frac{\sinh(c)}{c}
\end{equation}
$$
Indeed we can work out the solutions for any $$d > 1$$
$$
\begin{equation}
\langle e^{\bf{ c \cdot n}} \rangle = \frac{2^{d/2 - 1} \Gamma(d/2)}{c^{d/2 - 1}} I_{d/2 - 1} (c)
\end{equation}
$$
where $$\Gamma$$ is the Gamma function. The figure below shows agreement between the analytic results and evaluation of $$ \langle e^{\bf{ c \cdot n}} \rangle $$ via sampling points on a sphere, for some small values of $$d$$.

Higher order tensors should follow the same ideas - the averaged quantities should only depend on the (in general non-linear) invariants of the tensor. Quantities like
$$
\begin{equation}
\langle e^{\bf{n^T H n}} \rangle = \int e^{H_{ij} n_i n_j} \frac{d\Omega^d_{\bf n}}{S_d}
\end{equation}
$$
will be considered in a later post (i.e when i get to it).
References:
[1] NIST Digital Library of Mathematical Functions
<file_sep>/_posts/2019-02-04-notepad_rough.md
---
layout: post
title: ABP pdf
image: /img/hello_world.jpeg
tags: []
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
This is a calculation to determine the probability density of non-interacting, elliptical ABPs in a harmonic box trap.
The Fokker Plank (FP) is
$$
0 = \partial_x \Big( D\partial_x P + \mu \partial_x V P \Big) + \partial_{\theta} \Big( \tau^{-1} \partial_{\theta} P + \mu_r \partial_{\theta} U P \Big)
$$
<b>In the wall</b>: Assume Boltzmann weighted
$$
P = \mathcal{Z}^{-1} e^{-\frac{\mu}{D} V - \mu_r \tau U}
$$
<b>In bulk</b> ($$ U=0 \, V=0 $$) use a series solution
$$
P = \frac{\rho_0}{2\pi} + \frac{1}{\pi} \sum_i a_n \cos n \theta \cosh\Bigg(\frac{n (x - x_w/2)}{\sqrt{D \tau}} \Bigg) \tag{(1)} \label{eqn:bulk-pdf}
$$
Where we've used the symmetry about centre of the box.
Continuity of $$\mathcal{P}$$ spatially leads to matching at $$x=x_w$$
$$
\mathcal{Z}^{-1} \exp \big(-\lambda \kappa \mu_r \tau \cos(2\theta)/2 \big) = \frac{\rho_0}{2\pi} + \frac{1}{\pi} \sum_i a_n \cos n \theta \cosh\Bigg(\frac{n x_w}{2\sqrt{D \tau}} \Bigg) \label{eqn:dirichlet} \tag{(1)}
$$
Which upon solving gives us
$$
\rho_0 = \mathcal{Z}^{-1} 2 \pi I_0(\lambda \kappa \mu_r \tau/2)
$$
$$
a_{2n} = \mathcal{Z}^{-1} \frac{2 \pi I_n(-\lambda \kappa \mu_r \tau/2)}{ \cosh\Big( n x_w/\sqrt{D \tau} \Big)} $$
And from normaliation
$$
\mathcal{Z} = 2 \pi I_0(\lambda \kappa \mu_r \tau/2) ( x_w + \sqrt{2 \pi D/\lambda \mu} )
$$
So full solution is
$$
\begin{cases}
\frac{1}{I_0(\lambda \kappa \mu_r \tau/2) ( x_w + \sqrt{2 \pi D/\lambda \mu} } \exp \Big( -\mu V / D - \lambda \kappa \mu_r \tau \cos(2 \theta) /2 \Big) \\
\frac{1}{x_w + \sqrt{2 \pi D/\lambda \mu}} \Bigg( \frac{ 1 }{2\pi} + \frac{1}{\pi} \sum_n \frac{I_n(-\lambda \kappa \mu_r \tau/2)}{I_0(\lambda \kappa \mu_r \tau/2)} \frac{\cosh\Big(n (2x - x_w)/ \sqrt{D \tau}\Big) }{ \cosh\Big( n x_w/\sqrt{D \tau} \Big)} \cos 2 n \theta \Bigg)
\end{cases}
$$
<h3> Rotational Work </h3>
Should consider
$$ \langle \partial_{x_w} U \rangle \qquad \langle \partial_{\lambda} U \rangle $$
which give
$$ - \frac{\lambda \kappa}{2} \langle \delta(x - x_w) \cos 2 \theta \rangle \qquad \frac{\kappa}{2} \langle \cos 2 \theta \big[ H(-x) + H(x - x_w) \big] \rangle $$
We can calculate each component directly to get (ignoring $$\kappa/2$$)
$$ \frac{\lambda}{x_w + \sqrt{2 \pi D/\lambda \mu} } \frac{I_1(\lambda \kappa \mu_r \tau /2)}{I_0(\lambda \kappa \mu_r \tau/2 )} \qquad -\frac{\sqrt{2 \pi D/\lambda \mu }}{x_w + \sqrt{2 \pi D / \lambda \mu}}\frac{I_1(\lambda \kappa \mu_r \tau /2)}{I_0(\lambda \kappa \mu_r \tau/2)} \tag{2} \label{eqn:mixed-partials} $$
To check whether these form an exact differential we should calculate the difference between mixed partials
$$ \partial_{\lambda} \langle \partial_{x_w} U \rangle - \partial_{x_w} \langle \partial_{\lambda} U \rangle $$
Using
$$ d(I_1/I_0)/dx = 1 - \frac{I_1}{x I_0} - \Big( \frac{I_1}{I_0} \Big)^2 $$
Explicitly this gives us
$$
\begin{equation}
\begin{aligned}
\frac{1}{x_w + \sqrt{2 \pi D/\lambda \mu}} \frac{I_1}{I_0} &+ \frac{1}{2} \frac{\sqrt{2 \pi D / \lambda \mu}}{(x_w + \sqrt{2 \pi D/\lambda \mu})^2 } \frac{I_1}{I_0} + \frac{\lambda}{x_w + \sqrt{2 \pi D/\lambda \mu}} \Big( \frac{\kappa \mu_r \tau}{2} \Big) \Big( 1 - \frac{2 I_1}{\lambda \kappa \mu_r \tau I_0} - (\frac{I_1}{I_0})^2 \Big) \\
& - \frac{\sqrt{2 \pi D/\lambda \mu}}{(x_w + \sqrt{2 \pi D/\lambda \mu})^2 } \frac{I_1}{I_0} \\
& = - \frac{1}{2} \frac{\sqrt{2 \pi D / \lambda \mu}}{(x_w + \sqrt{2 \pi D/\lambda \mu})^2 } \frac{I_1}{I_0} + \frac{\lambda}{x_w + \sqrt{2 \pi D/\lambda \mu}} \Big( \frac{\kappa \mu_r \tau}{2} \Big) \Big( 1 - (\frac{I_1}{I_0})^2 \Big) \neq 0
\end{aligned}
\end{equation}
$$
Which is non-zero. This should be zero in equilibrium so maybe we should review our assumptions
<h5> i) Continuity </h5>
By multiplying the FP equation by a cosine and integrating we can derive the spatial equations for the angular moments.
$$
\tau^{-1} n^2 m_n + \frac{\lambda \kappa \mu_r n}{2} \big( m_{n-2} - m_{n+2} \big) = \partial_x \Big( \mu \partial_x V m_n + D \partial_x m_n \Big) \label{eqn:moments} \tag{3}
$$
The $$n = 0$$ case gives us an equation for the density, and we can confirm that the equation requires it to be continuous (we also expect this physically, but it is also present from a mathematical perspective).
$$
\begin{equation}
\begin{aligned}
0 &= \mu \int^{x_w + \epsilon}_{x_w - \epsilon} \partial_x V \rho + D \int^{x_w + \epsilon}_{x_w - \epsilon} \partial_x \rho \\
0 &= \mu \int^{x_w + \epsilon}_{x_w} \partial_x V \rho + D ( \rho^{+} - \rho^{-} ) \\
0 &= \lim_{\epsilon \rightarrow 0 } D ( \rho^{+} - \rho^{-} ) \qquad \checkmark
\end{aligned}
\end{equation}
$$
Let's repeat this for the higher moments to check for their mathematical continuity. Integrating Eq (\ref{eqn:moments})
$$
\tau^{-1} n^2 \int^{x_w + \epsilon}_{x_w - \epsilon} m_n dx + \frac{\lambda \kappa \mu_r n}{2} \int^{x_w + \epsilon}_{x_w} \big( m_{n-2} - m_{n+2} \big) = \mu \int^{x_w + \epsilon}_{x_w} \partial_x^2 V m_n dx + \mu \int^{x_w + \epsilon}_{x_w} \partial_x V \partial_x m_n dx + D \Big( \partial_x m_n \vert^{+} - \partial_x m_n \vert^{-} \Big) = 0
$$
Which leads to a continuity condition on the <i>gradients</i> of the moments $$ n > 0$$ across a boundary, rather than the moments themselves.
$$
0 = \lim_{\epsilon \rightarrow 0 } D \Big( \partial_x m_n \vert^{+} - \partial_x m_n \vert^{-} \Big)
$$
For $$\rho$$, both conditions hold. With this condition, let us again reexamine the solution to the FP equation. The dirichlet boundary condition in Eq \ref{eqn:dirichlet} is replaced by a Neumann condition. The first of the Dirichlet conditions concerning the density is un changed, but on top of this we also have that all $$ a_n =0 $$ for $$n>0$$. This returns us to the naive solution
$$
\begin{cases}
\frac{1}{I_0(\lambda \kappa \mu_r \tau/2) ( x_w + \sqrt{2 \pi D/\lambda \mu} } \exp \Big( -\mu V / D - \lambda \kappa \mu_r \tau \cos(2 \theta) /2 \Big) \\
\frac{1}{x_w + \sqrt{2 \pi D/\lambda \mu}} \frac{ 1 }{2\pi}
\end{cases}
$$
<h5> ii) Fluxes </h5>
Suppose we seek a solution which contains fluxes, such that within the wall
$$
D \partial_x P + \mu \partial_x V P = \mathcal{L}_x P = \partial_{\theta} f(x, \theta) \\
\tau^{-1} \partial_\theta P + \mu_r \partial_\theta U P = \mathcal{L}_{\theta} P = -\partial_x f(x, \theta) \\
$$
In the bulk we'll have
$$
D \partial_x P = \partial_{\theta} f_b(x, \theta) \\
\tau^{-1} \partial_\theta P = -\partial_x f_b(x, \theta) \\
$$
The usual flux free case is then the case where $$f (f_b) = $$const. We can solve these individual equations directly (here $$x > x_w$$)
$$
P(x, \theta) = \exp(-\mu V /D) \Big[ P(x =x_w, \theta) + \int_{x_w}^{x} \exp( \mu V(x') /D) \partial_{\theta} f(x', \theta) dx' \Big] \\
P(x, \theta) = \exp(-\mu_r \tau U ) \Big[ P( x, \theta = 0) - \int_0^{\theta} \exp( \mu_r \tau U(\theta')) \partial_{x} f(x, \theta') d\theta' \Big] \\
$$
We expect the spatial pdf to be BOltzmann weighted in both cases, so integrating with respect to $$\theta$$ should give us this spatial density. Integratig the second equation then gives
$$
P(x, \theta) = \Big[ I_0(\lambda \kappa \mu_r \tau/2) P( x, \theta = 0) -\int^{2\pi}_0 d\theta \exp( -\mu_r \tau U(\theta)) \int_0^{\theta} \exp( \mu_r \tau U(\theta')) \partial_{x} f(x, \theta') d\theta' \Big] \\
$$
This second term must then be equal to $$ \mathcal{A} \exp(-\mu V/D)$$, where $$ \mathcal{A}$$ could be $$0$$.
In the bulk we have
$$
D \partial_x P = \partial_{\theta} f_b(x, \theta) \\
\tau^{-1} \partial_\theta P = -\partial_x f_b(x, \theta) \\
$$
The bulk flux therefore obeys the same differential equation as the FP pdf itself within the bulk (by considering mixed partials in $$P$$). In full generality the solution is
$$
f_b(x,\theta) = \frac{1}{2\pi} f_b^{(0)} ( A + B x) + \frac{1}{\pi} \sum_n \sin (n\theta) \Big[ f_b^{(n, +)}\exp( n x/ \sqrt{D \tau} ) + f_b^{(n, -)} \exp(-n x/ \sqrt{D \tau})) \Big]
$$
They are not the same function however, because $$f_b$$ will have different boundary conditions and constraints.
The coefficients of $$f$$ are related to those of $$P$$ ($$a_n$$'s in Eq \ref{eqn:bulk-pdf} in the following way for $$n > 0$$
$$
f^{(n, \pm)}_b = \pm \frac{a_n}{2\sqrt{D^{-1} \tau}} e^{\mp n x_w/2 \sqrt{D \tau}} \\
B = 0
$$
Leading to ($$A \rightarrow 1$$ wlog)
$$
f_b(x,\theta) = \frac{1}{2\pi} f_b^{(0)} + \frac{1}{\pi \sqrt{D^{-1} \tau} } \sum_n a_n \sin (n\theta) \sinh \big( \frac{n (x - x_w/2)}{\sqrt{D \tau}} \big)
$$
$$f_b^{(0)}$$ seems similar to a gauge like freedom, so I suspect it can be set to 0 wlog. We can try a similar analysis on the wall region. It can be shown that $$f$$ obeys the pde
$$
\tau^{-1}\partial_{\theta}^2 f + D\partial_x^2 f + \mu_r \partial_{\theta} U \partial_{\theta}f + \mu \partial_x V \partial_x f = 0
$$
From here we can use seperation of variables to solve this within the wall
<b> iii) State equation </b>
We expect the work output to be 0 with any quasistatic protocol. Therefore we require that $$ \partial_{\lambda} \langle \partial_{x_w} U \rangle - \partial_{x_w} \langle \partial_{\lambda} U \rangle $$ vanishes.
Note that the only way for this to be identically zero we need
$$
\begin{equation}
\begin{aligned}
&\frac{\partial_{x_w} U }{\partial_\lambda U }= \frac{\partial_{x_w} P}{\partial_\lambda P} \\
\implies &\frac{\partial x_w}{\partial \lambda}\Big)_{U} = \frac{\partial x_w}{\partial \lambda}\Big)_{\rho}
\end{aligned}
\end{equation}
$$
Which would imply further that $$P = P(U)$$ i.e a state function. Generalising this idea, we make an ansatz that $$ P = P(U,V)$$, we can then write the FP equation in the following form (using expressions like $$\partial_V (\partial_x V) = 0$$)
$$
0 = D (\partial_x V)^2 \partial_V \big( e^{-V} \partial_V \big( e^V P \big) \big) + \tau^{-1} (\partial_\theta U)^2 \partial_U \big( e^{-U} \partial_U \big( e^U P \big) \big) + D \partial_xV \partial_x U \partial_U \partial_V P \\
0 = D (\partial_x V)^2 \partial_V \big( e^{-V} \partial_V \big( e^V P \big) \big) + \tau^{-1} (\partial_\theta U)^2 \partial_U \big( e^{-U} \partial_U \big( e^U P \big) \big) + D \partial_xV \partial_x U \partial_U \partial_V P
$$
<file_sep>/_posts/2019-03-22-stress-functions.md
---
layout: post
title: Stress Functions
image: /img/hello_world.jpeg
tags: [rheology, tensors, classical mechanics]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
In this post we'll discuss a certain description of stresses in 2D mechanical systems, which has proved useful in the study of granular systems and other such packings in mechanical equilibrium. It is called the <b> Airy stress function </b>, $$\psi$$.
Consider the stress tensor of an arbitrary 2D system $$ [\hat \sigma ] = \sigma_{ij}$$ which is a field over space (and time, if you wish, although we will look at the static case). Force balance is given by a divergenceless tensor $$ \nabla \cdot \hat \sigma = 0 $$ (as the normal forces on a volume should balance) and torque balance, which must be considered in frictinal systems, requires the tensor to be symmetric $$ \sigma_{ij} = \sigma_{ji}$$
The airy stress representation comes from us noticing that both of these force balance conditions can be met by writing
$$
\sigma_{ij} = \epsilon_{im} \epsilon_{jn} \partial_{m} \partial_{n} \psi \tag{1} \label{eqn:airy-stress}
$$
For some scalar field $$\psi$$. $$\epsilon_{ij}$$ is the totally anti-symmmetric tensor with $$\epsilon_`{12} = 1$$. The airy stress function is a <b> gauge field </b>, and so there is from freedom in it's representation ( similar to the freedom in defining a vector potential $${\bf A}$$ from a $${\bf B}$$ field in electromagnetism). As there are two derivatives in the Eq \ref{eqn:airy-stress} the stress is invariant under the transformation
$$
\psi \rightarrow \psi + {\bf a} \cdot {\bf r} + b
$$
for constant $${\bf a}, b$$. Such transformations clearly form a Lie group, called a <b> gauge group </b>. This function has been used extensively to study 2D elastic systems, and in these settings $$\psi$$ usually is determined by minimisaing some elastic energy functional. The contruction is general enough to handle even granular packings (under something something smoothness assumptions no doubt) which are not in thermal equilibrium and don't always deform elastically.
For 3D packings the representation is follows analogosly.
$$
\sigma_{il} = \epsilon_{ijk} \epsilon_{lmn} \partial_{j} \partial_{m} \Psi_{kn}
$$
Where $$\hat \Psi$$ is called the <b> Beltrami stress tensor </b>. The extra dimension saw us promote a scalar field to a rank 2 tensor field. By construction mechanical equilibrium is still satisfied. As before there is some gauge freedom, but this time it is a local symmetry transformation.
$$
\Psi_{ij} \rightarrow \hat \Psi_{ij} + \partial_i p_j({\bf r})
$$
For any vector field $${\bf p}$$. The gauge freedome is usually fixed using either the Maxwell gauge ($$ \Psi_{ij} = \delta_{ij} \phi_j$$) or the Morera gauge ($$\Psi_{ij} = 0 \text{ if } i = j$$) although of course there you can make up any gauge you like as long as it account for the right number of redundant DOFs.
We observe living in 3 spatial dimensions, but in light of [some work](https://arxiv.org/abs/1810.01213) that focuses on infinite dimnesional glasses, it might be interesting to deduce properties of the representation when $$d$$ become larger, past the $$d=3$$ we live in. More to come.
References:
[1] Edwards field theory for glasses and granular matter, <NAME> [link](https://)
[2] Statistical mechanics framework for static granular matter, <NAME> and <NAME> [link](https://)
<file_sep>/_posts/2018-11-23-recursive-methods-in-probability.md
---
layout: post
title: Recursive Methods in Probability
image: /img/hello_world.jpeg
tags: [probability, calculation methods]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Problems can of course be solved in mutliple ways. Sometimes the natural, methodical solution to a problem is very lengthy, so knowing some tricks is useful. One such trick is recursive reasoning, which can prove useful in certain types of probability problems and puzzles. I like these methods since the idea is sufficiently basic that anyone can use it without formal probabilistic training.
Consider the following problem:
<b> [Heads in a row]: </b> What is the expected number of coin flips to get n heads in a row?
So when n = 1 then the answer is obviously 2. One way to approach this problem in the general case is to define some family of expectations with a recursion relation connecting them. Define $$E_n$$ to be the expected number of coin flips needed to first get n heads in a row. The variables $$E_n$$ follow the recursion:
$$ E_{n+1} = \frac{1}{2} ( 1 + E_{n} ) + \frac{1}{2} ( 1 + E_{n+1} + E_{n} ) $$
This expression relies on the fact that to get $$n$$ heads in a row we must first have had $$n-1$$ heads in a row. Therefore from having $$n-1$$ heads 2 things can occur; either we get another head with a probability half (which would lead to just one more flip), or we get a tail and have to start from scratch. The solution to this is then $$E_n = 2 ( 2^{n} - 1)$$. If the coin is unfair and we have probability $$p$$ of getting a head, then the answer is $$(p^{-n} - 1 )/(1 - p)$$.
This is nice concept is an example of what is (apparently) called the "Law of iterated Expectations";
$$ E(X) = \sum_i E(X|A_i) P(A_i) $$
where X is some random variable and $$A_i$$ is a complete partition of the probability space. For the case above $$A_1 = n-1$$ heads just flipped and $$A_2$$ would be the complement.
Consider this one other problem:
<b> [Filling Boxes]:</b> You have $$N$$ boxes lined up in a row, and you need to fill each of them with an item. If you can'te remember which boxes you have already filled what is the expected number of box openings needed?
If we could remember the positions we have tried, then the we would of course need $$N$$ boxes exactly. In the memoryless case the answer can be derived via a recursive expression. Define $$E_m$$ to be the expected number of trials left to fill the remaining boxes, given we have already filled $$m < N$$ boxes. WIth this definition $$E_N = 0$$ and in particular we want $$E_0$$.
$$ E_{m} = \frac{m}{N} ( 1 + E_{m} ) + (1 - \frac{m}{N} )( 1 + E_{m+1} ) $$
this can then be rearranged and solved exactly
$$ \sum_{m=0}^{N-1} ( E_m - E_{m+1}) = E_0 = N \sum_{k = 1} ^N \frac{1}{k} $$
Asymptotically this number goes as $$\sim N \log N + \gamma N $$, where $$\gamma = 0.57721...$$ is the Euler-Mascheroni constant. This is opposed to $$N$$ for the case with perfect memory. There is some tradeoff between memory (space) and average number of trials (time). It is also worth noting that in the momryless case our worst case run time is essentially infinite, so there is a long tail of (low probability) instances where we pick the wrong boxes for far longer than the average protocol time.
As a bonus it would be nice to smoothly interpolate between perfect recall and memoryless. Luckily, recursive reasoning also makes this possible!
Let us now say we can remember a finite distance $$r < N $$ into our past i.e we can remember the last $$r$$ boxes we tried in a sort of "one-in-one-out" fashion. What is the expected number of trials to fill now? Using the recursion we can generalise to
$$ E_{m} = \frac{m - r}{N - r} ( 1 + E_{m} ) + \Big(1 - \frac{m - r}{N - r} \Big)( 1 + E_{m+1} ) \qquad m \geq r$$
Under a similar calculation as before this then leads to
$$ E_0 = r + (N - r ) \sum_{k = 1}^{N - r} \frac{1}{k} $$
Asymptotically we then have that $$E_0 \sim N(1-f) \log( N (1-f) ) + N f + N(1 - f) \gamma $$ for the case with memory, where we've defined $$f = r/N$$. So we have a smooth interpolation between the memoryless and perfect recall situations. I don't know of any other ways to do this problem that are nicer than this - recursive techniques are nice and simple.
TE
<file_sep>/_posts/2021-01-01-random-decreasing-seq.md
---
layout: post
title: Random Decreasing Sequence
image: /img/hello_world.jpeg
tags: [probability]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Suppose we have a decreasing sequence defined in the following way. First consider a random number generator $$R$$ that takes a non-negative integer, $$n$$, as input and returns one of $$\{0,1,...,n-1\}$$, the choice being made uniformly at random. Now pick some integer $$x_0$$ and define a sequence of $$x_i$$ by the recurrence relation:
$$
x_i = R(x_{i-1}) \qquad i \geq 1
$$
Clearly the sequence is strictly decreasing. Moreover it has some finite, non-deterministic running time ($$x_i=0$$ is an absorbing state). How long do we expect it to run for, given some (large) initial integer seed $$x_0$$?
We can solve this fairly rapidly using the **tower rule**. Let us call $$\mathcal{E}_r$$ the expected running time for $$x_{0} = r$$. Then
$$
\begin{equation}
\begin{aligned}
\mathcal{E}_{N} &= 1 \cdot \frac{1}{N} + \frac{1}{N} \sum_{k=1}^{N-1} (1 + \mathcal{E}_k) \\
& = 1 + \underbrace{\frac{1}{N} \sum_{k=1}^{N-1} \mathcal{E}_k}_{\mathcal{S}_{N-1}}
\end{aligned}
\end{equation}
$$
The labelled term $$S_N$$ has a rather simple recursion relation itself,
$$
\begin{equation}
\begin{aligned}
\mathcal{S}_{m-1} &= \frac{1}{m} \sum_{k=1}^{m-1} \mathcal{E}_k \\
&= \frac{1}{m} \mathcal{E}_{m-1} + \frac{m-1}{m} \frac{1}{m-1}\sum_{k=1}^{m-2} \mathcal{E}_k \\
&= \frac{1}{m} (1 + \mathcal{S}_{m-2}) + \frac{m-1}{m} \mathcal{S}_{m-2} \\
\implies \mathcal{S}_{m-1} &= \frac{1}{m} + \mathcal{S}_{m-2}
\end{aligned}
\end{equation}
$$
$$\mathcal{S}_1 = \frac{1}{2}$$, so we can clearly see that $$\mathcal{S}_m = \sum_{k=2}^{m+1} \frac{1}{k}$$ which gives us $$\mathcal{E}_{x_0} = \sum_{k=1}^{x_0} \frac{1}{k}$$. For large initial seed this is $$\approx \log(x_0)$$.
<file_sep>/research.md
---
layout: page
title: Research
---
I like science.
**Publications**
- <NAME>., <NAME>, **<NAME>**, <NAME>, and <NAME>. "Obreimoff revisited: Controlled heterogeneous fracture through the splitting of mica." Mechanics of Materials 136 (2019): 103088. ([link](https://www.sciencedirect.com/science/article/abs/pii/S0167663618307543))
- **<NAME>**, <NAME>, and <NAME>. “Thermodynamic Cycles with Active Matter.” Physical Review E 102, no. 1 (July 1, 2020): 010101. https://doi.org/10.1103/PhysRevE.102.010101. ([link](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.102.010101)) ([arXiv:2002.05932 (2020)](https://arxiv.org/abs/2002.05932))
- <NAME>., <NAME>, <NAME>, <NAME>, <NAME>, **<NAME>**, J<NAME> et al. "Inference, prediction and optimization of non-pharmaceutical interventions using compartment models: the PyRoss library." ([arXiv:2005.09625 (2020)](https://arxiv.org/abs/2005.09625)) .
- <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, **<NAME>**, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. "Efficient Bayesian inference of fully stochastic epidemiological models with applications to COVID-19" ([arXiv:2010.11783 (2020)](https://arxiv.org/abs/2010.11783))
**Presentations**
- _Berkeley Statistical Physics Conf (2019)_ - "Thermodynamic Cycles with Active Fluids" (flash talk)
- _DAMTP Statistical Physics and Soft Matter Seminar (2018)_ - "Designing Active Macroscopic Heat Engines"
- _NSTP Research Symposium (2017)_ - "Simulation of Arbitrary Grain Boundaries in Metallic Crystals)
**Code Packages**
- [PyRoss](https://github.com/rajeshrinet/pyross) (contributor)
<file_sep>/_posts/2020-07-19-entropy-post-XOR.md
---
layout: post
title: Entropy post XOR
image: /img/hello_world.jpeg
tags: [cryptography, probability]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
The XOR of two bit strings is a fundamental operation in computational logic and cryptography. For example, when implementing a One Time Pad, we encode a message and secret key as bytes and XOR both of these together.
A fundamental fact often used is that the result of a completely random bitstring XOR'ed against another bitstring, with any distribution, yields another completely random bitstring. This is easy to reason - suppose we have one length-$$\ell$$ bitstring $$r = \{0,1\}^{\ell}$$. Each bit is an iid RV which takes the value 0 or 1 with equal probability. Let $$m$$ be any other bit string of the same length, with arbitrary distributions on each bit. Consider the logic table for the first bits XOR'ed together:
$$r$$[0] | $$m$$[0] | $$r[0] \oplus m[0]$$ | prob. |
1 | 1 | 0 |$$p_1/2 $$|
0 | 1 | 1 |$$ p_1/2$$|
1 | 0 | 1 |$$ p_0/2$$|
0 | 0 | 0 |$$p_0/2$$ |
We can see the output is uniform distributed on the output bit, regardless of the distribution of the bitstring $$m$$. Intuitively this makes some sense, the randomness stored in $$r$$ is not diminished when combined (in a reversible way) with another source of randomness. A uniformly distibuted bit has maximal "randomness", so the amount of randomness also can't increase by adding another source of randomness. To be more precise, the appropriate measure of "randomness" is the Shannon entropy
$$ H_2(p) = -\big( p \ln(p) + (1-p) \ln(1-p) \big) $$
What if we have two bit strings which are to be XOR'ed, but neither of them are uniformly random? From the above argument we don't ever expect the entropy to decrease, but since neither bit is maximally entropic there is room for the result to be "more random". Let us make this more concrete.
Suppose we once again have two bitstrings of length $$\ell$$, both of which have iid's determining the value of each of their bit according to different ditributions. Call the strings $$x_i$$ with probability of a 1 $$p_i$$ for $$i$$=A,B. Their resulting bitstring after XOR will be called $$x_C$$. The probability of 1 on the first bit of $$x_C$$ is
$$
\begin{equation}
p_C = p_A(1-p_B) + p_B(1 - p_A) = p_A + p_B(1 - 2p_A)
\end{equation}
$$
Since $$p_C$$ is a wighted average between two probabilites, its value will be mean regressing i.e it will get closer to 0.5. As the Shannon entropy has a global maximum at $$p=1/2$$ this means the entropy of the distribution will increase. So two biased, uncorrelated distributions can be combined to produce a more uniform, more "random" one. No comment on whether this a good idea in practice.
(These statements could be see in terms of inequalities on the entropy itself. $$ H(X_1) \leq H(X_1, X_2)$$ states that upon mixing the inputs, the entropy can't decrease.)
<file_sep>/_posts/2018-12-17-an-integral.md
---
layout: post
title: An Integral
image: /img/hello_world.jpeg
tags: [statistical physics, approximation]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
A function of this form came up while doing calculations on active particle dynamics
$$ f(x ; \alpha, \beta, \gamma) = e^{-\beta x^2/2} \int^{\pi}_{-\pi} \frac{d\theta}{2 \pi} \exp \big(\alpha x \cos \theta - \gamma \cos^2 \theta \big) \label{eqn:f-function} \tag{1} $$
All the parameters of $$f$$ are non-negative, but the variable $$x$$ can take any real value. The function is defined implicitely in terms of this integral which has no closed form expressions which Mathematica could identify. We can still look at interesting properties of this expression, even if we can't find a closed form for it.
For the physical situation this arises from, $$\gamma$$ will typically be a small variable compared to $$1$$. So a natural thing to try would be to expand the second term in the integrated exponential in a taylor series. This then gives us an infinite sum for $$f$$ in terms of <b> Modified Bessel Functions </b>
$$ I_k (x) = \int_0^{\pi} \frac{d\theta}{\pi} \cos (k \theta) \exp( x \cos \theta) $$
for integer $$k$$. Our function then can written using the Bessels as a positional basis. Using the symmetry properties of the bessels, we write
$$ f = e^{- ( \gamma + \beta x^2)/2} \Big( I_0(\gamma/2)I_0(\alpha x) + 2\sum_{k=1}^{\infty} (-1)^k I_k(\gamma/2) I_{2k}(\alpha x) \Big) $$
From here we can truncate at some order to yield an approximation to the function. We might also be interested in the asympototic tails of this function - i.e its behaviour as $$x \rightarrow \pm \infty$$. Let us focus on divergence in positive values first. One way to approximate its behaviour is by noting that Eq. $$\eqref{eqn:f-function}$$ would be peaked around $$\theta = 0$$ for sufficiently large, positive $$x$$. Using a saddle point approximation about this point we get that
$$ f \approx e^{- (\gamma + \beta x^2) /2} \int ^{\infty}_{-\infty} \frac{d\theta}{2 \pi} \exp \Big( \alpha x \Big[1 - \frac{1}{2} \theta^2 \Big] - \frac{1}{2} \gamma \Big[ 1 - \frac{1}{2} (2 \theta)^2 \Big] \Big) $$
$$ f \sim e^{- (2 \gamma + \beta x^2 - 2 \alpha x ) /2} \Bigg( \sqrt{\frac{1}{2 \pi \alpha x}} + \mathcal{O}(x^{3/2}) \Bigg) $$
Our function $$f$$ is also even in $$x$$, so the same asymptote holds as we diverge negatively (although in the interim calculation we must expand about the <i>minimum</i> of $$\cos$$). Where are the stationary points of this function in $$x$$? Since it is even around the origin, there will surely be one there, but are there any more? To help calculation we look for the staionary points of $$ \log f$$ instead.
$$0 = - \beta x + \alpha \frac{\int d\theta \cos\theta \exp(\alpha x \cos \theta - \gamma \cos^2 \theta) }{\int d\theta \exp( \alpha x \cos \theta - \gamma \cos^2 \theta )} := \Pi(x) \label{eqn:Pi} \tag{2} $$
There a couple of key observations to make here. For $$x \rightarrow \infty$$ the first term is negative and decreases indefinitely without bound, but the second term is always bounded between $$(-\alpha,\alpha)$$ (since $$ \vert \cos \theta \vert \leq 1$$), and tends to $$\alpha$$ as $$x \rightarrow \infty$$. Therefore there is either one solution only (at $$x = 0 $$), or three depending on the relative values of the parameters.
The second function is concave, so it is enough to consider the linear behaviour of both terms about $$x=0$$. If the gradient of the first term is initially larger or the same as the gradient of the second, then we have one solution to $$\Pi = 0$$, otherwise we'll have three. The first is already linear, but the second can be expanded about $$x=0$$.
$$ \Pi(x) \approx \Bigg[ - \beta + \frac{\alpha }{2} \Big( 1 - \frac{I_1(\gamma /2)}{I_0(\gamma /2)} \Big) \Bigg] x + \mathcal{O}(x^3) $$
Again, using the definition of the Bessel functions. And so we therefore need the following condition for a stationary point away from the origin.
$$ \beta < \frac{\alpha }{2} \Big( 1 - \frac{I_1(\gamma /2)}{I_0(\gamma /2)} \Big) $$
This is the same behaviour seen in equilibrium second order phase transitions (such as mean field Ising model). Just from graphical arguments, we then see that $$f$$ goes from something which has a maximum at $$x=0$$ and decays at both sides, to something with a minimum at $$x=0$$ and maxima further out, before decaying away. The simplest way to approximate the location of the stationary points $$\pm x_p$$ is to just take the next order, which is fine if you expect the maxima to not be too far from the origin. The calculation for it is not too illuminating though. Some bounds may give a more intuitive picture instead.
We can easily say that $$0 \leq x_p <\alpha/ \beta $$ from examining Eq. $$\ref{eqn:Pi}$$, but maybe there is something nicer we can do.
References:
[1] NIST Digital Library of Mathematical Functions
<file_sep>/_posts/2020-03-03-resetting-basics.md
---
layout: post
title: Plastic Events and Resets
image: /img/hello_world.jpeg
tags: [statistical physics, rheology, quantum mechanics]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Imagine a stochastic reset of a certain type. Each site of our rheologicla material has a stress associtaed with it, but due to mechanical noise (rather than thermal fluctations) the stress at each site is going to fluctuate according to some effective Stochastic ODE i.e for each site (assuming they are statistically identical):
$$
\dot{\sigma}_i = - \mu V_0 ' (\sigma_i) + \eta
$$
Where for simplicity we've taken the noise to be white and gaussian. On top of this we have added a local potential, which is simoply to do with the elastic nature of each site. For example, by imposing external stresses on our rheological sample we might find that the local stresses ten dot relax down to some typical steady value due to elastic restoring forces.
Now we've said something about how local stresses evolve, but how do they relax? In real rheological flows we often have plastic reorganisation events when the system locally overcomes its yield stress $$ \sigma_Y$$. So imagine a model where we reset with some constant rate $$r$$ if the magnitude of the local stress is above the yield stress. Using a <a href=""> recent stochastic path integral formulation</a>, we could write this as
$$
P_{\text{no reset}}(x, t) = \int \mathcal{D} \sigma(t) \exp(-S_{\text{res}}[\sigma(t)]) \\
\text{with} \\
S_{\text{res}} = \int^t_0 dt \Bigg[ \frac{ [(d\sigma/dt) - \mu F ]^2 }{4D} + \frac{\mu F'}{2} + r(\sigma) \Bigg]
$$
Where $$F = - V_0 '$$ and $$r(\sigma) = H(\sigma - \vert \sigma_Y \vert )$$. This formalism allows us to map unto a 1D schrodinger equation, where many solution and approximations methods are known. In this case the effective Hamiltonian can be written
$$ H = -\frac{1}{2 m_{\text{eff}}} \partial_x^2 + V_{\text{eff}} \\
\text{where} \\
m_{\text{eff}} = (2D)^{-1} \qquad V_{\text{eff}} = \frac{\mu^2 F^2}{4 D} + \frac{\mu F'}{2} + r(\sigma)
$$
With this connection, and some more manipulation of probabilities, the steady state dynamics of resetting stress can be studied using the Green's function of the associated quantum problem.
<file_sep>/_posts/2019-04-01-active-energetics.md
---
layout: post
title: Active Energetics (in progress)
image: /img/hello_world.jpeg
tags: [thermodynamics, stochastic processes]
math: true
---
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
Let us call $$ \phi(x, \theta)$$ the ABP potential function. This can take various forms depending on the model. Let's impose that $$ \phi$$ and its derivative is zero at the wall for all $$\theta$$ The steady state Fokker Plank equation for this system is then
$$
0 = \partial_x \big( ( \mu \partial_x \phi - v \cos \theta ) \mathcal{P} + D \partial_x \mathcal{P} \big) + \partial_{\theta} \big( \tau^{-1} \partial_{\theta} \mathcal{P} + \mu_r \partial_{\theta} \phi \mathcal{P} \big) \tag{1} \label{eqn:fokker-plank}
$$
Even without the active propulsion, there is still some peculiarity in the system in the general case. From the stochastic ODEs the spatial and angular degree of freedom both fluctuate, but at at <i>different temperatures</i>. When these degrees of freedom do not interact (i.e $$\phi = \phi_1(x) + \phi_2(\theta)$$) and $$ v = 0$$ then the system is a standard equilibrium one since from independence of the DOFs we expect $$ \mathcal{P} (x, \theta) = \mathcal{P}_1(x) \mathcal{P}_2(\theta)$$ with each . But if we have a general $$\phi$$ then $$x$$ and $$\theta$$ are coupled, which can lead to non equilibrium currents even in the absence of a self propulsion velocity. This is in line with [previous considerations]( https://tekeh.github.io/2019-03-22-thermal-beads/ ).
As coupling can introduce phase space currents, it is not obvious that we will be guaranteed zero work processes, even without self propulsion, in a physical system of this type. Indeed the [previous post](https://) linked to above shows that for a simple 2 node elastic chain we can extract work from out stochastic thermodynamic framework. Because of this trying to get zero work results simply by changing the potential seem like they would not work. The original potential function from before is in some ways more convenient as the coupling is "weak" in some sense with only the heaviside term multiplying the angular energy.
We can integrate this equation over all angles $$\theta $$, and then assume no spatial flux to yield the condition
$$
0 = \mu \int^{2 \pi}_0 \partial_x \phi \mathcal{P} d\theta - v m_1 + D \partial_x \rho \label{eqn:zero-flux} \tag{2}
$$
where $$m_n(x) = \int^{2 \pi}_0 \mathcal{P} \cos n\theta \quad d\theta $$. If we multiply by $$\cos n\theta$$ first beforewe integrate we instead get the moment equation
$$
\partial_x \big( ( \mu \int^{2\pi} \cos n\theta \partial_x \phi \mathcal{P} d\theta - \frac{v}{2} (m_{n+1} + m_{n-1} ) + D \partial_x m_n \big) = n^2 \tau^{-1} m_n - n \mu_r \int^{2\pi}_0 \cos n\theta \partial_{\theta} \phi \mathcal{P} d\theta
$$
The definition of the mechanical pressure on the right hand side wall in the system is
$$
\begin{equation}
\begin{aligned}
P &= \int_{x_w}^{\infty} \int^{2\pi}_0 \mathcal{P} \partial_x \phi dx d\theta \\
&= \mu^{-1} \int_{x_w}^{\infty} \big( v m_1 - D \partial_x \rho \big) dx \\
&= \frac{v}{\mu} \int_{x_w}^{\infty} m_1 dx + \frac{D}{\mu} \rho_0
\end{aligned}
\end{equation}
$$
With $$\rho_0 = \rho(x_w)$$. Integrating Eq \ref{eqn:fokker-plank} over all positions yields a similar zero flux condition.
$$
0 = \tau^{-1} \partial_{\theta} f(\theta) + \mu_r \int^{\infty}_{-\infty} \partial_{\theta} \phi \mathcal{P} dx
$$
The work output for a 2 parameter harmonic wall is, following the framework of stochastic thermodynamics
$$
\begin{equation}
\begin{aligned}
d \mathcal{W} &= \langle \partial_{x_w} \phi \rangle d x_w + \langle \partial_{\lambda} \phi \rangle d \lambda \\
&= - P d x_w + \langle \partial_{\lambda} \phi \rangle d \lambda
\end{aligned}
\end{equation}
$$
We will now look specifically at some potential functions
<h3> Product Form $$ \phi = \phi_1(x) \phi_2(\theta) $$ </h3>
In this specific case let us use
$$
\phi_1 = \lambda\Big[ x^2 H(-x) + (x - x_w)^2 H(x - x_w) \Big] \quad \phi_2 =\kappa \cos 2 \theta + 1
$$
For this potential $$ \langle \partial_{\lambda} \phi \rangle = \lambda^{-1} \langle \phi \rangle $$. We can calculate it in the following way, within the right hand wall
$$
\begin{equation}
\begin{aligned}
\langle \phi \rangle &= \lambda \int_{x_w}^{\infty} \int_0^{2\pi} (x - x_w)^2 (\kappa \cos(2\theta) + 1 ) \mathcal{P} dx d\theta \\
&= \frac{1}{2} \int_{x_w}^{\infty} \int_0^{2\pi} (x - x_w) \partial_x \phi \mathcal{P} dx d\theta \\
&= \frac{1}{2} \int_{x_w}^{\infty} (x - x_w) (v m_1 - D \partial_x \rho) dx \\
&= \frac{1}{2} D \int^{\infty}_{x_w} \rho(x) dx + \frac{v}{2} \int_{x_w}^{\infty} (x - x_w) m_1 dx
\end{aligned}
\end{equation}
$$
when $$ v = 0 $$ we have the simple expression
$$
d \mathcal{W} = - \frac{D}{\mu} \rho(x_w) d x_w + \frac{D}{2 \lambda \mu} \Big( 2 \int_{x_w}^{\infty} \rho(x) dx \Big) d \lambda
$$
When $$v = 0$$ the [solution for the density profile in the bulk must be flat](link), therefore we write $$ \rho(x_w) = (\mathcal{N} - \mathcal{N}_w)/x_w $$.
$$
d \mathcal{W} \propto -\mathcal{N} d(\ln x_w ) + \mathcal{N}_w d ( \ln x_w \lambda^{1/2} )
$$
As $$\mathcal{N}$$ is a constant the first term will disappear under a loop integral. Thus only the second term is worth investigating. The term will vanish only if $$\mathcal{N}_w$$ depends on the potential parameters only through the form implied by the differential i.e $$ \mathcal{N}_w = \mathcal{N}_w( x_w \lambda^{1/2}) $$. This is manifestly true if we assume a spatial boltzmann distribution everywhere. We need to calculate $$\mathcal{N}_w$$ within this model. Using Eq \ref{eqn:zero-flux} we have that $$ D \partial_x \rho = - \mu \partial_x \phi_1 ( \kappa m_2 + \rho) $$, Integrating up gives
$$
\rho = \rho(x_w) e^{ - \frac{\mu}{D} \phi_1} - \frac{\kappa \mu}{D} e^{- \frac{\mu}{D} \phi_1} \int_{x_w}^{x} \partial_t \phi_1 m_2 e^{ \frac{\mu}{D} \phi_1} dt
$$
After some more calculation, and a couple of changes of variable we can show that
$$
\mathcal{N}_w/ \mathcal{N} = \frac{\sqrt{2 \pi D/ \lambda \mu }}{x_w + \sqrt{2 \pi D/ \lambda \mu} } \Bigg[ 1 - \frac{\kappa x_w}{\mathcal{N}} \int_0^{\infty} \frac{d \bar u}{\sqrt{\pi}/2} e^{-\bar u^2 /2} \int_0^{\bar u} d \bar z \partial_{\bar z} \Big( e^{\bar z ^2/2} \Big) m_2 ( \sqrt{\frac{D}{\lambda \mu}} \bar z + x_w ) \Bigg]
$$
The first term is the first, uncorrected term, and scales in the appropriate way as to derive zero work output. The second term (related to the [Dawson function?]( https://en.wikipedia.org/wiki/Dawson_function )) is the correction due to the imbalance of temperatures in this model (remember here $$v = 0$$). This term would need to produce the specific funcitonal dependence necessary for zero work, which we should not expect a priori.
When the thermal bath flucuations match this is definitely satisfied. By noting the full distribution will be given by a Boltzmann (verifiable by substituting answer into Fokker Plank equation) we get that
$$
m_2( \bar z\sqrt{ D/\lambda \mu} + x_w ) = \mathcal{N} \frac{e^{-\bar z^2 /2} I_1(\kappa \bar z^2/2)}{x_w + I_0(\kappa \bar z ^2 /2) \sqrt{2 \pi D / \lambda \mu }} \quad \text{ (inside wall) }
$$
Which clearly satisfies the necessary functional form for the number of particles in the wall, and thus will give zero work output under all cyclic protocols.
For the general temperature imbalance we can calculate the work output to first order in the difference. Let us wrtie Eq \ref{eqn:} $$ \mathcal{L} \mathcal{P} = 0$$. We wish to peturb away from an exactly soluble limit. Take $$ (\tau \mu_r)^{-1} = D/\mu $$ - in this limiit Eq \ref{eqn:} will be written $$ \mathcal{L}_0 \mathcal{P}_0 = 0$$. $$ \mathcal{P}_0$$ is then the Boltzmann solution. Now suppose that the temperatures are nearly the same, with $$ \tau \mu_r = \frac{\mu}{D} (1 + \epsilon) + \mathcal{O}(\epsilon^2)$$. We can also expand our solution to first order so that $$ \mathcal{P} = \mathcal{P}_0 + \epsilon \mathcal{P}_1 + \mathcal{O}(\epsilon^2)$$ and collect terms to first order to yield
$$
(\mathcal{L}_0 + \epsilon \mathcal{L}_1 ) ( \mathcal{P}_0 + \epsilon \mathcal{P}_1 + ...) \\
\rightarrow \mathcal{L}_1 \mathcal{P}_0 = - \mathcal{L}_0 \mathcal{P}_1
$$
The LHS can be quickly computed
$$
\mathcal{L}_1 \mathcal{P}_0 = \frac{\phi_1 \mu}{\tau D^2} \Big( \frac{\mu \kappa}{D} ( 1 - \cos 4 \theta ) \phi_1 - 4 \kappa \cos 2 \theta \Big) \mathcal{P}_0 \equiv ( a_0 + a_2 \cos 2 \theta + a_4 \cos 4 \theta )\mathcal{P}_0 \\
\text{where} \\
\mathcal{L}_1 f = \frac{\mu}{\tau D^2} \partial_{\theta} \Big( \partial_{\theta} \phi f \Big)
$$
We can then expand the first order correction to the distribution as a fourier series $$ \mathcal{P}_1 = \rho^{\epsilon}/(2 \pi) + \pi^{-1} \sum m_n^{\epsilon} \cos (n \theta )$$. We can then compare the coefficients
$$
\partial_x \Big( \partial_x m^{\epsilon}_n + \frac{1}{T} \partial_x \phi_1 \big[ m^{\epsilon}_n + \frac{\kappa}{2} ( m^{\epsilon}_{n+2} + m^{\epsilon}_{n-2} ) \big] \Big) - \frac{n^2}{\tau D} + \frac{2 n \kappa}{\tau D T} \phi_1 (m^{\epsilon}_{n+2} - m^{\epsilon}_{n-2}) \Big) \\
= a_0 m_n + \frac{a_2}{2} ( m_{n-2} + m_{n+2} ) + \frac{a_4}{2} ( m_{n-4} + m_{n+4} ) \tag{3} \label{eqn:moments}
$$
We wish to calculate the particle number
$$
\begin{equation}
\begin{aligned}
\mathcal{N}_w &= 2 \int_{x_w}^{\infty} ( \rho_0(x) + \epsilon \rho_1(x) ) dx \\
&= \mathcal{N}_w^{(0)} + 2 \epsilon \int^{\infty}_{x_w} \rho_1 dx \\
\end{aligned}
\end{equation}
$$
Using Eq \ref{eqn:moments} with $$n = 0$$ gives
$$
2 \pi \frac{\phi_1^2 \mu^2 \kappa }{\tau D^3} = \partial_x \Big( \frac{\mu}{D} \partial_x \phi_1 ( \kappa a_2 + \rho_1 ) + \partial_x \rho_1 \Big)
$$
<h3> Weak Addtitive Form $$ \phi = \phi_1(x) + \phi_2(\theta) [ H(-x) + H(x - x_w) ] $$ </h3>
Called "weak addtive" because, in a sense, this is one of the weakest couplings as there is no functional dependenc on the $$x$$ for the $$\phi_2$$ apart from ht Heaviside. This is essentially the form initially investigated, ave for the boundary impulse term. For specificity, take
$$
\phi_1 = \lambda\Big[ x^2 H(-x) + (x - x_w)^2 H(x - x_w) \Big] \quad \phi_2 = \lambda \kappa \cos 2 \theta
$$
<h3> General Mixed Form $$ \phi = \phi(x, \theta)$$ </h3>
I'm not sure much can be said about this case which hasn't been said already. In general will be the hardest to solve for. In this specific case let us use
$$
\phi = \lambda \Bigg( \Big[ (x - x_w)^2 + (x - x_w) (\kappa \cos 2 \theta + 1) \Big] H(x - x_w) + \Big[ x^2 + x (\kappa \cos 2 \theta + 1) \Big] H(-x)
$$
I'm not sure much can be done with this case directly.
<file_sep>/blog.md
---
layout: page
title: Blog
---
_A collection of posts of variable length, detail, and lucidity. Most fall into the category of "Calculations and expositions I want immediate access to from anywhere with WiFi"._
<ul>
{% for post in site.posts %}
<li>
<a href="{{ post.url }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
|
b18c43b109c9506da50affb9988733505a99de19
|
[
"Markdown"
] | 24 |
Markdown
|
tekeh/tekeh.github.io
|
052c18f84748ad155ea0a3aea8cfb301b0c61206
|
0923fa830127922153c3806bf4ab0aac1cd771b0
|
refs/heads/master
|
<file_sep># Hello-World
Test only
Add some more description!
|
82d5058d0ff12c44d5284975091e0643aead84ec
|
[
"Markdown"
] | 1 |
Markdown
|
tassadar1985/Hello-World
|
f2b7871387b823b7220ec7412871cca5a7498089
|
c25748efbfccfa16bf5f920a83cb9d95800b8dac
|
refs/heads/master
|
<repo_name>samuelkaiser/SpringMVC<file_sep>/src/main/java/edu/wctc/credit/CreditCardFormController.java
package edu.wctc.credit;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/credit")
public class CreditCardFormController {
@RequestMapping("/showForm")
public String showForm(){
return "credit/credit-form";
}
@RequestMapping("/review")
public String reviewDetails(HttpServletRequest request, Model model){
// Map<String, String> cardDetails = new HashMap<>();
String securityCode = request.getParameter("securityCode");
String cardNumber = request.getParameter("cardNumber");
String nameOnCard = request.getParameter("nameOnCard");
String expirationDate = request.getParameter("expirationDate");
model.addAttribute("securityCode", securityCode);
model.addAttribute("cardNumber", cardNumber);
model.addAttribute("nameOnCard", nameOnCard);
model.addAttribute("expirationDate", expirationDate);
// cardDetails.put("cardNumber", request.getParameter("cardNumber"));
// cardDetails.put("nameOnCard", request.getParameter("nameOnCard"));
// cardDetails.put("expirationDate", request.getParameter("expirationDate"));
// cardDetails.put("securityCard", request.getParameter("securityCard"));
return "credit/credit-review";
}
}
<file_sep>/src/main/webapp/WEB-INF/view/credit/credit-form.jsp
<%--
Created by IntelliJ IDEA.
User: skaiser4
Date: 2020-02-18
Time: 20:26
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Credit Card Form</title>
</head>
<body>
<c:url value="/credit/review" var="actionUrl" />
<form method="get" action="${actionUrl}">
<input type="text" name="cardNumber" placeholder="1234 5678 9012 3450" />
<input type="text" name="nameOnCard" placeholder="nameOnCard" />
<input type="text" name="expirationDate" placeholder="MM/YY" />
<input type="text" name="securityCode" placeholder="CVC" />
<input type="submit" id="reviewDetails">
</form>
</body>
</html>
<file_sep>/target/springmvc/WEB-INF/view/simple/simple-form.jsp
<%--
Created by IntelliJ IDEA.
User: skaiser4
Date: 2020-02-18
Time: 19:33
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:url value="/simple/shout" var="actionUrl" />
<form id="simple-form" method="get" action="${actionUrl}">
<input type="text" name="studentName" id="studentName1" placeholder="Student Name" />
<!--<input type="text" name="studentEmail" id="studentEmail" placeholder="Student Email" />
<input type="text" name="studentId" id="studentId" />
<input type="text" name="" id="" />
<input type="text" name="" id="" />
<input type="text" name="" id="" />-->
<input type="submit" id="shoutSubmit">
</form>
<c:url value="/simple/shoutAgain" var="actionUrlAgain" />
<form id="simple-form2" method="get" action="${actionUrlAgain}">
<input type="text" name="studentName" id="studentName2" placeholder="Student Name" />
<!--<input type="text" name="studentEmail" id="studentEmail" placeholder="Student Email" />
<input type="text" name="studentId" id="studentId" />
<input type="text" name="" id="" />
<input type="text" name="" id="" />
<input type="text" name="" id="" />-->
<input type="submit" id="shoutAgainSubmit">
</form>
</body>
</html>
<file_sep>/target/springmvc/WEB-INF/view/home.jsp
<%--
Created by IntelliJ IDEA.
User: skaiser4
Date: 2020-02-18
Time: 18:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1><a href="finaid/home">Go to financial Aid</a></h1>
<h1><a href="registrar/home">Go to registrar</a></h1>
<img src="resources/images/astronaut.jpg" alt="should be an astronaut but nobody's perfect" />
<h1><a href="simple/showForm">Go to simple form</a></h1>
<h1><a href="credit/showForm">Go to credit form</a></h1>
</body>
</html>
<file_sep>/README.md
# SpringMVC
## First ever actual project using Spring MVC
<file_sep>/src/main/webapp/WEB-INF/view/main-menu.jsp
<h1>Main Menu Test</h1>
|
34b98f536f6696f9faffc47227e3ac7d0060bef7
|
[
"Java",
"Markdown",
"Java Server Pages"
] | 6 |
Java
|
samuelkaiser/SpringMVC
|
31a8b302908ca868bcec75f34e2f09de6145d208
|
efaf388c20b999a53bf71f3eadffc53452ba6b9e
|
refs/heads/main
|
<repo_name>mbezot/froposters-mern<file_sep>/backend/data/products.js
const products = [
{
name: '<NAME>',
image: '/images/carte-des-vins-de-france-poster-affiche-frog-posters.jpg',
description:
'Cette carte des vins de France regroupe les principales appellations et les cépages les plus répandus pour chaque région viticole.',
brand: 'Frog Posters',
category: 'A boire !',
price: 28.00,
countInStock: 100,
rating: 5.0,
numReviews: 13,
},
{
name: '<NAME>',
image: '/images/pieces-de-boucherie-poster-affiche-frog-posters.png',
description:
'Idéal pour se faire mousser lors de barbecues et dîners : soyez incollable sur la découpe du boeuf à la française, et la découpe de la viande d’agneau, de porc et la volaille ! Ce tableau de boucher vous remettra à l’esprit tous les morceaux de boucherie.',
brand: 'Frog Posters',
category: 'A taaable !',
price: 28.00,
countInStock: 0,
rating: 5.0,
numReviews: 21,
},
{
name: '<NAME>',
image: '/images/guide-du-vrai-lyonnais-poster-affiche-frog-posters.jpg',
description:
'Vous êtes un vrai Lyonnais fier de votre ville ou vous souhaitez visiter Lyon ? Voici le guide ultime du VRAI Lyonnais. Retrouvez les 50 choses à savoir ou faire pour être vraiment Lyonnais : se donner rendez-vous sous la queue du cheval, déguster des huîtres aux halles, éviter la Part Dieu le weekend… Toutes ces petites choses indispensables qui rendent Lyon unique !',
brand: 'Frog Posters',
category: 'C est chez nous ',
price: 28.00,
countInStock: 50,
rating: 5,
numReviews: 3,
},
{
name: '<NAME>',
image: '/images/guide-des-rhums-du-monde-poster-affiche-frog-posters.jpg',
description:
'Vous retrouverez dans cette affiche les meilleurs Rhums du monde, comment ils sont élaborés et leur pays d’origine.',
brand: 'Frog Posters',
category: 'A boire !',
price: 28.00,
countInStock: 11,
rating: 5,
numReviews: 12,
},
{
name: 'Guide des bières',
image: '/images/guide-des-bieres-par-pays-poster-affiche-frog-posters.png',
description:
'Retrouvez dans cette affiche les différents types de bière par fermentation, pays d’origine, couleur et degré d’amertume.',
brand: 'Frog Posters',
category: 'A boire !',
price: 28.00,
countInStock: 7,
rating: 3.5,
numReviews: 10,
},
{
name: 'Guide des Cocktails',
image: '/images/guide-des-cocktails-poster-affiche-frog-posters.jpg',
description:
'Pour vos soirées détente ou entre amis, découvrez les plus grands cocktails du monde et leurs recettes dans cette affiche !',
brand: 'Frog Posters',
category: 'A boire !',
price: 28.00,
countInStock: 0,
rating: 4,
numReviews: 12,
},
]
export default products
<file_sep>/frontend/src/index.css
main {
min-height: 80vh;
}
h3 {
padding: 1rem 0;
}
h1 {
font-size: 1.8rem;
padding: 1rem 0;
}
h2 {
font-size: 1.4rem;
padding: 0.5rem 0;
}
.rating span {
margin: 0.1rem;
}
/* carousel */
.carousel-item-next,
.carousel-item-prev,
.carousel-item.active {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center; /* alignement vertical */
}
.carousel-caption {
}
.carousel-caption h3 {
color: #fff;
}
.carousel img {
max-height: 300px;
max-width: 225px;
padding: 1rem;
}
.carousel a {
}
@media (max-width: 900px) {
.carousel-caption h2 {
font-size: 2.5vw;
}
}
<file_sep>/README.md
# froposters-mern
# froposters-mern
|
e40d5b03a41b24f99057ff71dc3b31d7931e22d5
|
[
"Markdown",
"JavaScript",
"CSS"
] | 3 |
Markdown
|
mbezot/froposters-mern
|
3284a18c42fd7ca0df6d52bb4eddc0bd8b405632
|
bd46cf87499a78401f9030c44a9cda8390302cb7
|
refs/heads/master
|
<file_sep># 商店街のお店
<div align="center">
<img src="syou.jpg" width="20%">
<img src="nore.jpg" width="20%">
<img src="na.jpg" width="20%">
<img src="kaf.jpg" width="20%">
</div>
# 連携店の外観
<div align="center">
<img src="kafe.jpg" width="20%">
<img src="mi.jpg" width="20%">
<img src="tera.jpg" width="20%">
<img src="ramen.jpg" width="20%">
</div>
<file_sep>theme: jekyll-theme-cayman
title: titel
description: ex
github:
is_project_page:false
|
9fa48975fe26e247ecdee4ebbaae21c967cb135d
|
[
"Markdown",
"YAML"
] | 2 |
Markdown
|
mitukawa/web
|
e6841b81be895b0864e8ec0086777ad1dc495bcb
|
f486bd32c2971a8f37cb6c6a5a00a7aa46b92933
|
refs/heads/master
|
<repo_name>rasmuslp/eslint-config-rasmuslp<file_sep>/.eslintrc.json
{
"root": true,
"extends": "./src/javascript.js"
}
<file_sep>/src/javascript.js
const common = require('./common');
module.exports = {
extends: [
...common.extends
],
plugins: [],
rules: {
...common.rules,
// Possible Errors
// Best Practices
// Variables
// Node
// Stylistic
indent: ['error', 'tab', { SwitchCase: 1 }]
}
};
<file_sep>/.editorconfig
root = true
[*]
charset = utf-8
indent_style = tab
indent_size = 2
trim_trailing_white_space = true
insert_final_newline = true
[*.md]
trim_trailing_white_space = false
[*.{yml,yaml}]
indent_size = 2
indent_style = space
<file_sep>/src/common.js
exports.extends = [
'eslint:recommended',
'plugin:n/recommended',
'plugin:promise/recommended',
'plugin:unicorn/recommended'
];
exports.rules = {
// Possible Errors
'getter-return': 'error',
'no-console': 'warn',
// Best Practices
'consistent-return': 'off',
curly: 'error',
'default-case': 'error',
'no-void': 'off',
'require-await': 'off',
// Variables
// Node
'callback-return': 'off',
'n/callback-return': 'error', // Migrated from ESLint in ESLint 7
// Stylistic
'brace-style': ['error', 'stroustrup'],
'no-lonely-if': 'error',
'no-nested-ternary': 'error',
'no-tabs': 'off',
'quote-props': ['error', 'as-needed'],
semi: ['error', 'always'],
'space-before-function-paren': ['error', { anonymous: 'never', named: 'never', asyncArrow: 'always' }],
// Unicorn
'unicorn/filename-case': 'off',
'unicorn/prefer-module': 'off',
'unicorn/prevent-abbreviations': [
'error',
{
replacements: {
fn: false,
func: {
fn: true
},
i: false,
j: false
}
}
]
};
<file_sep>/README.md
# @rasmuslp/eslint-config
[](https://www.npmjs.com/package/@rasmuslp/eslint-config)
[](https://github.com/rasmuslp/eslint-config-rasmuslp/actions)
This configuration is based on [eslint-config-airbnb-typescript](https://github.com/iamturns/eslint-config-airbnb-typescript), but with a few tweaks and most notibly:
* indentation: tab
## Configurations
This project provides both a JavaScript and a TypeScript configuration file. **Defaults to** TypeScript.
## Installation
Install the config:
```bash
$ npm install --save-dev @rasmuslp/eslint-config
```
### NB: For npm 6 the peer dependencies also needs to be installed manually.
See peer dependencies:
```bash
$ npm info "@rasmuslp/eslint-config@latest" peerDependencies
```
Automatically install peer dependencies:
```bash
$ npx install-peerdeps --dev @rasmuslp/eslint-config
```
## Usage
Configure eslint in your project by extending this configuration in your local `.eslintrc.json`
```json
{
"root": true,
"parserOptions": {
"project": "./tsconfig.eslint.json"
},
"extends": [
"@rasmuslp"
]
}
```
The TypeScript config is utilized by certain rules that require type information.
To lint all project files, besides what the default `tsconfig` does, add `tsconfig.eslint.json` with:
```json
{
"extends": "./tsconfig.json",
"include": ["./"]
}
```
Lastly, specify the minimum supported Node version in `package.json` to enable checks for using unsupported Node features.
```json
"engines": {
"node": ">=16.13.0"
}
```
### TypeScript and React
Install additional dependencies
```bash
$ npm install --save-dev eslint-config-airbnb
```
Configure eslint in your project by extending this configuration in your local `.eslintrc.json`
```json
{
"root": true,
"extends": [
// Load broader rules first
"airbnb",
"airbnb-typescript",
// Then override with more specific rule set
"@rasmuslp/eslint-config/src/typescript-react"
]
}
```
### JavaScript
You can omit installing `@typescript-eslint/eslint-plugin` and `typescript`, but you will get warnings about missing peer dependencies.
Configure eslint in your project by extending this configuration in your local `.eslintrc.json`
```json
{
"root": true,
"extends": "@rasmuslp/eslint-config/src/javascript"
}
```
|
145c8a22bfaf4417663805e66b0c52aba1c3f0dc
|
[
"JSON with Comments",
"Markdown",
"JavaScript",
"EditorConfig"
] | 5 |
JSON with Comments
|
rasmuslp/eslint-config-rasmuslp
|
5a5f96a46eb44a2e5a44b991179979dffb1335e3
|
05e360489a157698511479c466487760da1e668f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.