Randomly take an int element from an integer array Posted: 15 May 2021 08:15 AM PDT I have an Integer array and i want to randomly take an element from those who are not null. I have tried this but after the else i cannot use return because the method is int . But i dont know what to write after else in order to return at the beggining and take a new random element. public int getRandomPosition(){ Random x = new Random(); int b = x.nextInt(2*number0fCardPairs); if (myArray[b] != null){ return b; } else{ return; } } |
Can't spawn enoguh Spark executors (limited to 8?) Posted: 15 May 2021 08:15 AM PDT For a Tensorflow Script I need precisely 12 Spark executors to run simultaneously on my three-node cluster (each 32/64-cores, 4 graphics-cards). I cannot find resources on the internet that really help me. There is spark.executor.instances , and together with spark.resource.gpu.amount I can change the needed slots somewhat, but for me it's a trial and error approach, and also I am getting nowhere. When I set 2 GPUs per executor, TF asks for 6 slots. But then Spark does only spawn 4 executors (two on one node, one on each other node). When I set 1 GPU per executor, TF asks for 12. Then Spark spawns up to eight executors (three on two nodes, two on the other one), but it still doesn't work. All this is independent from my spark.executor.instances setting. I can limit my executors with this, but if I set it to like 24 or something like this, it still does only spawn 4 or 8 executors respectively. From my description it becomes clear that I do not really know what to do. The official documentation gives somewhat of a impression of what the config-keys are meant to do, but it doesn't change anything for me. Does someone have valuable resources on how to achieve my goal? I'll be happy to provide more infos if needed. Thanks in advance! |
Imported Variables are given a NameError Posted: 15 May 2021 08:15 AM PDT So I've been wanting to create a basic Spotify bot that inputs lyrics in a text box. However, I am stopped by a NameError code which I'm not sure how to solve. MusicBot.py: (Main) from Spotify import get_current_track,main from Opening import browser,enter import json import requests import time start = time.perf_counter() #Variables main() artist = artist_names song_title = track_name # keywords = {'phone'} url = "https://api.lyrics.ovh/v1/" + artist + "/" + song_title response = requests.get(url) json_data = json.loads(response.content) lyrics = json_data['lyrics'] browser() enter(lyrics) finish = time.perf_counter() print(f"Test 3 took {finish} seconds")``` Spotify.py (where I want to import from to get the track_name & artist_names info): ```import requests import time from pprint import pprint SPOTIFY_GET_CURRENT_TRACK_URL = 'https://api.spotify.com/v1/me/player/currently-playing' ACCESS_TOKEN = '--' def get_current_track(access_token): response = requests.get( SPOTIFY_GET_CURRENT_TRACK_URL, headers={ "Authorization": f"Bearer {access_token}" } ) json_resp = response.json() track_id = json_resp['item']['id'] track_name = json_resp['item']['name'] artists = [artist for artist in json_resp['item']['artists']] link = json_resp['item']['external_urls']['spotify'] artist_names = ', '.join([artist['name'] for artist in artists]) current_track_info = { "id": track_id, "track_name": track_name, "artists": artist_names, "link": link } return current_track_info def main(): current_track_id = None current_track_info = get_current_track(ACCESS_TOKEN) if current_track_info['id'] != current_track_id: pprint( current_track_info, indent=4, ) current_track_id = current_track_info['id'] if __name__ == '__main__': main() The name errors I'm given is: Traceback (most recent call last): File "c:\Users\amanm\Desktop\Python\Python Crash Course\Part 2\LyricBot\MusicBot.py", line 12, in artist = artist_names NameError: name 'artist_names' is not defined |
UnityEngine screen size fit every Android device Posted: 15 May 2021 08:15 AM PDT How can I make my game screen fit every Android device. The problem every answer I find is for 2d. I want for 3d games. |
Set JSON Naming Convention for Refit client Posted: 15 May 2021 08:15 AM PDT I'm trying to use the Refit library (https://github.com/reactiveui/refit) to create an http client for my service, but there was a problem. I want to use SystemTextJsonContentSerializer for serialization and set the naming convention of json object properties for the request body. However, I did not find in the documentation how to do this. There is only an example for NewtonsoftJsonContentSerializer (see https://github.com/reactiveui/refit#json-content). How can this be done for SystemTextJsonContentSerializer ? |
Unstructured invoice data frame into multiple columns Posted: 15 May 2021 08:15 AM PDT I am new to this forum and I need some help to tidy this data frame into 5 different columns: 'invoice no', 'name', 'address', 'zip', 'extra' I encountered a few problems as there are no patterns at all. These are 'invoice no' issued (CM3398, G113524, etc) it is stuck together with the 'name' Sometimes the 'zip' is together with the 'address' and there are 3 and sometimes 4 rows after the 'invoice no'. As for the extra column it is for those with additional requirements like line 16. This is just a sample of the whole data set: invoice 0 CM3398 MIRANA 1 BLK 3015 2 #04-14 3 486350 4 G113524 JAYDEN 5 BLK 27 6 #01-174 7 539208 8 GA12917 AMAZON 9 23 CHURCH STREET 10 CAPITAL SQUARE 11 49481 12 GD15669 DELIVERY 13 PANDAMART 14 143 CECIL 15 GB BULDING 069542 16 (DELIVERY TIMING: 8AM-3PM) 17 GH12290 HANGUK 18 2 SENOKO 19 #05-03 20 758096 21 GH15289 HAWA 22 70 TAMPINES 23 #02 24 529681 |
No device driver found while installing windows Posted: 15 May 2021 08:15 AM PDT Here is the situation, I was trying to install Windows 10 on my PC. I have cleaned the hard disk (including the C drive which contained my Windows OS) and started installation with my bootable usb. I was getting an error called "No device driver found". I tried changing usb stick to different ports but the problem still exists. I have tried the same usb stick for my laptop to check whether the Windows installation is corrupted or not, and it was working perfectly fine. After that I searched and found that by installing intel rapid storage drivers might fix the issue but I was not able to install it because my bootable usb is not visible in the browse section. It only shows C drive (which is empty), a disk drive and a boot drive (but it does not contain those files). Later, I thought of using DVD for the device drivers and tried installing but it gave an error that either files are not correct or they are not present in installation media. I can even burn Windows iso on DVD as the size of iso file is larger than my DVD. I tried diskpart list disk # But this shows only my harddrive and not my usb stick, even if I connect multiple usb stick. I have 6 different ports available but none of them worked in detecting it. clean create partition primary format fs=ntfs exit I also tried installing Windows 7 but the same issue persist. In short, I am not able to install any of the Windows OS. Can anyone please help. THANK YOU! |
reset input text by clicking outside vue Posted: 15 May 2021 08:15 AM PDT I have an autocomplete field. If i put any text and it matches the result set then it will populate the dropdown result. If it doesn't match anything then by clicking outside it will reset the input field forcefully. So, for this approach i have created the vue click outside directive import Vue from 'vue'; const nodeList = []; const ctx = '@@clickoutsideContext'; let startClick; const counter = 0; const isServer = Vue.prototype.$isServer; /** * added this on event function for direct dom manipulation */ const onEvent = (function() { if (!isServer && document.addEventListener) { return function(element, event, handler) { if (element && event && handler) { element.addEventListener(event, handler, false); } }; } return function(element, event, handler) { if (element && event && handler) { element.attachEvent(`on${event}`, handler); } }; })(); !isServer && onEvent(document, 'mousedown', e => { startClick = e; }); !isServer && onEvent(document, 'mouseup', e => { nodeList.forEach(node => node[ctx].documentHandler(e, startClick)); }); // setting up mouse events function createDocumentHandler(el, binding, vnode) { return function(mouseup = {}, mousedown = {}) { if ( !vnode || !vnode.context || !mouseup.target || !mousedown.target || el.contains(mouseup.target) || el.contains(mousedown.target) || el === mouseup.target || (vnode.context.popperElm && (vnode.context.popperElm.contains(mouseup.target) || vnode.context.popperElm.contains(mousedown.target))) ) return; if ( binding.expression && el[ctx].methodName && vnode.context[el[ctx].methodName] ) { vnode.context[el[ctx].methodName](); } else { el[ctx].bindingFn && el[ctx].bindingFn(); } }; } /** * v-clickoutside * @desc Only trigger when click outside * @example * ```vue * <div v-element-clickoutside="handleClose"> * ``` */ export default { bind(el, binding, vnode) { nodeList.push(el); const id = counter + 1; el[ctx] = { id, documentHandler: createDocumentHandler(el, binding, vnode), methodName: binding.expression, bindingFn: binding.value }; }, update(el, binding, vnode) { el[ctx].documentHandler = createDocumentHandler(el, binding, vnode); el[ctx].methodName = binding.expression; el[ctx].bindingFn = binding.value; }, unbind(el) { const len = nodeList.length; for (let i = 0; i < len; i += 1) { if (nodeList[i][ctx].id === el[ctx].id) { nodeList.splice(i, 1); break; } } delete el[ctx]; } }; Autocomplete field is working fine. I am not able to understand how this directive will be used to reset input field. Any suggestions or examples will be helpful to understand. |
Logic wrong in custom loop on permissions authorization filter Posted: 15 May 2021 08:15 AM PDT Im getting false positives here basically what I want to happen is. It should only return an error if say for example the user does not have permission to do Create but at present its returning an error all the time when he has that permissions. User | Permission | Active | 12 | Create | True | 12 | Update | False | 12 | Delete | True | First Example [HasPermission("Create"); Should Return True it does but false positive, because read update and delete are not present. Second Example [HasPermission("Create,Update"); Should return false but is but is also returning that read and delete is not present when am only asking for create and update Code: string[] permissionValues = permission.Split(","); Dictionary<string, bool> dict = new Dictionary<string, bool>(); foreach (var item in permissionValues) { var permissions = db.AppWarehouseUserPermmissions.Any(w => w.Name == item && w.Controller == controllerName && w.isAcitve == true); dict.Add(item, permissions); } foreach (var item in dict) { if (item.Key == "Create" || item.Key == "Read" || item.Key == "Update" || item.Key == "Delete" && item.Value == true) { isAuthorised = true; } if (item.Key == "Create" || item.Key == "Read" || item.Key=="Update" || item.Key=="Delete" && item.Value==false) { _customError.Add(new CutomError() { Message = $"User has no {item.Key} permissions", ErrorCode = item.Key }); } } return isAuthorised; |
java.lang.NoClassDefFoundError: javax/annotation/Generated in Adroid studio Posted: 15 May 2021 08:14 AM PDT I faced this error while trying to run an app source code that I got from Github on android studio. please how can I solve it? I tried setting the JDK home in my gradle.properties file in the root of the project to the JDK bundled with Android Studio: org.gradle.java.home=/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home But I got this error: Value '/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home' given for org.gradle.java.home Gradle property is invalid (Java home supplied is invalid) This is the build output: > Task :app:compileDebugJavaWithJavac Task :app:compileDebugJavaWithJavac in app Starting file or directory 'C:\Users\Ahmed Guedmioui\AndroidStudioProjects\MovieBox films\app\libs', not found Caching disabled for task ':app:compileDebugJavaWithJavac' because: Build cache is disabled Task ':app:compileDebugJavaWithJavac' is not up-to-date because: Task has failed previously. All input files are considered out-of-date for incremental task ':app:compileDebugJavaWithJavac'. Gradle may disable incremental compilation as the following annotation processors are not incremental: realm-annotations-processor-5.3.0.jar (io.realm:realm-annotations-processor:5.3.0), dagger-compiler-2.5.jar (com.google.dagger:dagger-compiler:2.5). Consider setting the experimental feature flag android.enableSeparateAnnotationProcessing=true in the gradle.properties file to run annotation processing in a separate task and make compilation incremental. Compiling with source level 1.8 and target level 1.8. file or directory 'C:\Users\Ahmed Guedmioui\AndroidStudioProjects\MovieBox films\app\libs', not found Full recompilation is required because no incremental change information is available. This is usually caused by clean builds or changing compiler arguments. file or directory 'C:\Users\Ahmed Guedmioui\AndroidStudioProjects\MovieBox films\app\src\debug\java', not found file or directory 'C:\Users\Ahmed Guedmioui\AndroidStudioProjects\MovieBox films\app\build\generated\aidl_source_output_dir\debug\compileDebugAidl\out', not found file or directory 'C:\Users\Ahmed Guedmioui\AndroidStudioProjects\MovieBox films\app\build\generated\renderscript_source_output_dir\debug\compileDebugRenderscript\out', not found Compiling with JDK Java compiler API. Note: Version 10.5.0 of Realm is now available: https://static.realm.io/downloads/java/latest Note: Processing class MovieRealmObject Note: Creating DefaultRealmModule Task :app:compileDebugJavaWithJavac in app Finished > Task :app:compileDebugJavaWithJavac FAILED :app:compileDebugJavaWithJavac (Thread[Execution worker for ':' Thread 2,5,main]) completed. Took 3.526 secs. AAPT2 aapt2-3.5.1-5435860-windows Daemon #0: shutdown Execution failed for task ':app:compileDebugJavaWithJavac'. > java.lang.NoClassDefFoundError: javax/annotation/Generated * Try: Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output. Run with --scan to get full insights. This is my build.gradle: apply plugin: 'com.android.application' apply plugin: 'realm-android' def getProperty(String filename, String propName) { def propsFile = rootProject.file(filename) if (propsFile.exists()) { def props = new Properties() props.load(new FileInputStream(propsFile)) if (props[propName] != null) { return props[propName] } else { print("No such property " + propName + " in file " + filename) } } else { print(filename + " does not exist!") } } android { compileSdkVersion 29 buildToolsVersion '28.0.3' defaultConfig { applicationId "com.esoxjem.movieguide" minSdkVersion 21 targetSdkVersion 29 versionCode 1 versionName "1.0" buildConfigField "String", "TMDB_API_KEY", "\"${getProperty("local.properties", "tmdb_api_key")}\"" buildConfigField "String", "TMDB_BASE_URL", "\"https://api.themoviedb.org/\"" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } lintOptions { disable 'InvalidPackage' } packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' exclude 'META-INF/rxjava.properties' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } ext { supportLibVersion = '28.0.0' okhttpVersion = '4.2.2' daggerVersion = '2.5' espressoVersion = '3.0.2' } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) //Support implementation 'com.google.android.material:material:1.0.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.annotation:annotation:1.1.0' implementation 'androidx.palette:palette:1.0.0' implementation 'androidx.recyclerview:recyclerview:1.1.0' implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' // Rx implementation 'io.reactivex.rxjava2:rxjava:2.2.14' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' //RX View Binding implementation 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.2.0' // Network implementation "com.squareup.okhttp3:okhttp:${okhttpVersion}" implementation "com.squareup.okhttp3:logging-interceptor:${okhttpVersion}" implementation 'com.github.bumptech.glide:glide:4.2.0' // Other implementation 'net.jcip:jcip-annotations:1.0' implementation 'com.google.guava:guava:18.0' implementation 'com.squareup.moshi:moshi:1.9.2' implementation 'com.jakewharton:butterknife:10.2.0' annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0' // Dependency Injection annotationProcessor "com.google.dagger:dagger-compiler:${daggerVersion}" implementation "com.google.dagger:dagger:${daggerVersion}" compileOnly 'javax.annotation:jsr250-api:1.0' // Retrofit 2 implementation 'com.squareup.retrofit2:retrofit:2.6.2' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.2' implementation 'com.squareup.retrofit2:converter-moshi:2.6.2' // Tests testImplementation 'junit:junit:4.12' testImplementation 'org.mockito:mockito-core:3.1.0' androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', { exclude group: 'com.android.support', module: 'support-annotations' }) androidTestImplementation('androidx.test.espresso:espresso-contrib:3.1.0') { exclude group: 'com.android.support', module: 'support-annotations' exclude group: 'com.android.support', module: 'appcompat' exclude group: 'com.android.support', module: 'support-v4' exclude module: 'recyclerview-v7' } androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test:rules:1.2.0' } |
I can't fix this problem in python, every time i save a file, it makes it list again and again Posted: 15 May 2021 08:14 AM PDT def dn_tsk(string): # To remove done tasks with open("tsk.txt", "r+") as file: data = file.readlines() data = str(data) for items in range(1): word = data.replace(string, " ") print(word, end=" ") file_rd = file.read() print(file_rd) with open("tsk.txt", "w") as file: file.write(word) #w = file.readlines() #print(w) |
Remix JS VM returns value, Ganache does not Posted: 15 May 2021 08:14 AM PDT I have a simple contract that: - Increments variable
val - Emits log with
val - Returns
val pragma solidity 0.8.4; contract MyContract { uint256 val; event Log(uint256 _val); function increment() external returns (uint256) { val++; emit Log(val); return val; } } Remix "Javascript VM" emulator logs the expected value and returns the expected value. However, Ganache (version 2.5.4; connected in Remix IDE through Web3 provider 127.0.0.1 ), logs the expected value but returns nothing. What causes this difference? |
Java: How to get the difference between two years? [Year Today and the Book Published Year] Posted: 15 May 2021 08:14 AM PDT I'm trying to get the number between two years from Now (2021) to the year on JTextField, which depends on the book that the user will choose and it will automatically display the book year chosen on JTextField. Here's my code so far: import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.util.Date; //when the JButton was clicked it will performed the following code //getting today's year int yearToday = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear(); int bookYear = Integer.parseInt(bookPublishedYear.getText()); //getting the published Year of the book //converting to String String yearToday1 = Integer.toString(yearToday); String bookYear1 = Integer.toString(bookYear); LocalDate tYear = LocalDate.parse(yearToday1); LocalDate bYear = LocalDate.parse(bookYear1); //getting the duration between two years Period period = Period.between(tYear, bYear); numberBetween.setText(String.valueOf(period.getYears())); //displaying the difference on the JTextField But, I'm getting these errors :/ Exception in thread "AWT-EventQueue-0" java.time.format.DateTimeParseException: Text '2021' could not be parsed at index 4 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400) at java.time.LocalDate.parse(LocalDate.java:385) |
How to launch multiple animated objects, each with a delay (Jetpack Compose)? Posted: 15 May 2021 08:15 AM PDT Currently, I have one tile travelling from bottom to top in an infinite loop. This is the code I am using: val infiniteTransition = rememberInfiniteTransition() val durationMillis = remember { mutableStateOf(5000) } val delayMillis = remember { mutableStateOf(0) } val positionState = infiniteTransition.animateFloat( initialValue = 0f, targetValue = 1f, animationSpec = infiniteRepeatable( animation = tween( durationMillis = durationMillis.value, delayMillis = delayMillis.value, easing = LinearEasing ) ) ) I am trying to launch several of these tiles in the same direction at various intervals, indefinitely. I don't want to wait until one has reached the top to launch another and I want each tile to reach the top before disappearing. So this is the code I am using to increase the delay for each new tile: } else if (index >= 7) { placeable.placeRelative( constraints.maxWidth - tileSize, yPosition - placeable.height * 7 + verticalAnimationPositioning, 1f ) delayMillis.value += 1000 } And verticalAnimationPositioning is this: val verticalAnimationPositioning = (constraints.maxHeight - (constraints.maxHeight * positionState.value)).toInt() This does nothing. What happens is that all my tiles travel at the same time and disappear as soon as the first one reaches the top. Do you have any idea how I can achieve having the tiles travel independently at intervals? |
Error: Column not found: 1054 Unknown column 'p_categories.id' Posted: 15 May 2021 08:14 AM PDT For my laravel project, I created the product category table and add data to the table. Now I need to get each product_category detail using get method. This is the product category table that I created, public function up() { Schema::create('p_categories', function (Blueprint $table) { $table->bigIncrements('category_id'); $table->string('name'); $table->string('size'); $table->timestamps(); }); } CategoryController I use, <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\PCategory; class CategoryController extends Controller { // function addPCategory(Request $req) { $pcategory=new PCategory; $pcategory->name=$req->input('name'); $pcategory->size=$req->input('size'); $pcategory->save(); return $pcategory; } function getCategory($id) { return PCategory :: find($id); } } In api.php I use, Route :: post('addPCategory',[CategoryController::class,'addPCategory']); Route :: get('Category/{id}',[CategoryController::class,'getCategory']); I am getting this error in postman Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'p_categories.id' in 'where clause' (SQL: select * from `p_categories` where `p_categories`.`id` = 1 limit 1) Thank you in advance for your help! |
How to include a c++ library in a c project using Cmake Posted: 15 May 2021 08:14 AM PDT I'm a begginer on c, c++ and Cmake. I'm trying to add two external cpp libraries to a c project but is has being very difficult. (https://github.com/adafruit/DHT-sensor-library) (https://github.com/adafruit/Adafruit_Sensor) I'm importing the libraries like this: INCLUDE_DIRECTORIES(lib/Adafruit_Sensor) LINK_DIRECTORIES(lib/Adafruit_Sensor) INCLUDE_DIRECTORIES(lib/DHT-sensor-library) LINK_DIRECTORIES(lib/DHT-sensor-library) But I'm getting an error message when compiling the c++ libraries. error: unknown type name 'class' Could anyone plis enlight me on how to do this? Many thanks! |
How to get a time span between two methods in c#? Posted: 15 May 2021 08:15 AM PDT I am trying to make a stopwatch with C# as an exercise for myself. my plan was to make two methods " start()" and " stop()" then call these from my stopwatch class in my main. the problem I have is that I do not know how to get the time span between these two. for your information, this is how I want the program to work: if they typed s the timer starts and when press enter or type f the time will be shown to them. this is the code I have written so far, but got stuck when getting the time span. class StopWatch { DateTime starting = DateTime.Now; DateTime finishing = DateTime.Now; public void start() { Console.WriteLine(starting); } public void stop() { Console.WriteLine(finishing); } } class Program { static void Main(string[] args) { Console.WriteLine("type s to start and f to stop"); var input = Console.ReadLine(); var stopwatch = new StopWatch(); if (input.ToLower() == "s") { stopwatch.start(); } var Input2 = Console.ReadLine(); if (Input2.ToLower() == "f") { stopwatch.stop(); } Console.ReadKey(); } } |
Why does switching order of OR statement fix TypeError: '<=' not supported between 'str' and 'int'? Posted: 15 May 2021 08:15 AM PDT I am doing some basic data validation, and I'm confused. I have the following function: def is_int_gt2(num): if num <= 2 or type(num) != int: return False else: return True When I call is_int_gt2(-1) I get False . And when I call is_int_gt2(5) I get True . So far so good. But if I call is_int_gt2('a') , I get TypeError: '<=' not supported between instances of 'str' and 'int' What confuses me, however is that when I switch the order of the conditions in the or statement, the function works perfectly!: def is_int_gt2(num): if type(num) != int or num <= 2: return False else: return True So now I have a working function, but I don't know why. Why does switching the order of the condition fix the function? Thank you. |
Read access violation when using %s format specifier Posted: 15 May 2021 08:14 AM PDT I've been trying to write a program that takes a string as a input, and output will be the same string written in morse code, however in getting reading access violation, while using %s format specifier with *(mors + i). #include <stdio.h> #include <stdlib.h> #include <string.h> #pragma warning(disable : 4996) void code(char litery[], const char* mors) { char arr[256]; printf("string to be coded:\n"); fgets(arr, 256, stdin); for (int counter = 0; counter < strlen(arr); ++counter) { if (arr[counter] == ' ') { printf(" "); } int i; for (i = 0; i < 36; ++i) { if (arr[counter] == litery[i]) { printf("%s", *(mors + i)); break; } } } } int main() { char litery[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}; const char* mors[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----" }; code(litery, *mors); } |
Sorting Sequence Of Images By Features Posted: 15 May 2021 08:14 AM PDT I want to sort a sequence of images that have overlaps. Currently I match all the images's features and select the longest sequence in which there is a minimum matching threshold between the images. This way is not effective at all! Is there another way? |
Discord.py Server Lockdown Command Posted: 15 May 2021 08:15 AM PDT I would like to add a command to lockdown an entire server and revert the lockdown. It works, but it changed ALL the channels send messages permission to False/True. I'm asking if there is a way to set the permissions to neutral and not to change channel permissions if it is already false or true. Here is my current code: #Lockdown @client.command() @commands.has_permissions(manage_channels=True) async def lockdown(ctx): for channel in ctx.guild.channels: await channel.set_permissions(ctx.guild.default_role, send_messages=False) await ctx.send('The server is now on lockdown!') #unlockdown @client.command() @commands.has_permissions(manage_channels=True) async def unlockdown(ctx): for channel in ctx.guild.channels: await channel.set_permissions(ctx.guild.default_role, send_messages=True) await ctx.send('Server is now unlocked') |
have an admin & user routing structure in angular Posted: 15 May 2021 08:16 AM PDT I want to create an angular app with 2 separate modules for Admin panel and the site's front-end which I use lazy-loading for modules. Now I want to don't show header and footer components when user goes to /admin route , here is my code: app.component.html <app-header></app-header> <router-outlet></router-outlet> <app-footer></app-footer> and here is my project structure: app - admin -login component -dashboard component -admin.module -admin.routing.module -... - pages -home component -products component -... - shared app.component app.module app.routing.module ... Can you assist me what should I do? what is the best practice? Thanks a lot |
Document query selector returns undefined in react Posted: 15 May 2021 08:15 AM PDT I am trying to build a toggle sidebar. when I click on the button the class list of .m-toggle should be updated. But react gives me an error "TypeError: Cannot read property 'classList' of null" Here is my code: import React, { useState, useEffect } from 'react' // import Sidebar from '../Components/Sidebar' import AppleIcon from '@material-ui/icons/Apple' import DashboardIcon from '@material-ui/icons/Dashboard' import PeopleIcon from '@material-ui/icons/People' import NotificationsIcon from '@material-ui/icons/Notifications' import SettingsIcon from '@material-ui/icons/Settings' import HelpIcon from '@material-ui/icons/Help' import img from '../Assets/img/keval.jpg' function toggleMenu() { let toggle = document.querySelector('.m-toggle') toggle.classList.toggle('m-active') } const Main = () => { return ( <> <div className="m-body"> <div className="m-container"> {/* -------Sidebar Start------- */} <div className="m-navigation"> <ul style={{ padding: '0' }}> <li> <a href="#"> <span className="m-icon"> <AppleIcon className="muicon" /> </span> <span className="m-title"> <h2>Brand Name</h2> </span> </a> <hr style={{ color: 'white' }} /> </li> <li> <a href="#"> <span className="m-icon"> <DashboardIcon className="muicon" /> </span> <span className="m-title">Dashboard</span> </a> </li> <li> <a href="#"> <span className="m-icon"> <PeopleIcon className="muicon" /> </span> <span className="m-title">Employees</span> </a> </li> <li> <a href="#"> <span className="m-icon"> <NotificationsIcon className="muicon" /> </span> <span className="m-title">Notification</span> </a> </li> <li> <a href="#"> <span className="m-icon"> <HelpIcon className="muicon" /> </span> <span className="m-title">Help</span> </a> </li> <li> <a href="#"> <span className="m-icon"> <SettingsIcon className="muicon" /> </span> <span className="m-title">Setting</span> </a> </li> </ul> </div> {/* --------Side BAr End--------- */} <div className="m-main"> <div className="m-topbar"> <div className="m-toggle" onClick={toggleMenu()}> f </div> <div className="m-search"> <label> <input type="text" placeholder="Search here" /> </label> </div> <div className="user"> <img src={img} alt="no img" /> </div> </div> </div> </div> </div> </> ) } export default Main You can see the code where onclick class list should be updated but it is not updating. |
Is there any if function to skip NA values in excel Posted: 15 May 2021 08:15 AM PDT Hi All, I am trying to use average function where it can skip the NA values. As per attached snapshot how can i get the result of correct one which is 200/3. I want to take the count of NA but not while calculating average. I can's use 0 because the value will be calculated as well like the sAMPLE2 snapshot. Please advise. |
How to print columns if only a specific values is matched in a Linux? Posted: 15 May 2021 08:15 AM PDT I have a sample.txt file like this: abc shk ansjc def xyz dkksk ghd ssk jshhd djsh xyz dsoop ssd swl jsjdl I want to print column1 & column2 but column2 can be printed if only the content is matching with "xyz", so the output will be as follows. abc def xyz ghd djsh xyz ssd This is what I tried so far, awk '$2 == "xyz" { print $1,$2 }' output2.txt || awk '$2 != "xyz" { print $1 }' Can anyone help me to get this output? |
Multiple data insertion in async writing in apache geode Posted: 15 May 2021 08:14 AM PDT we have Apache Geode which is connected to Postgres and AsyncCache writer is configured to write data to postgres. In Async write we submit the list of events which we want to persist and it asynchronously insert those events. Let's say i have two client application which calls processEvents for async writing and both have some events common which violate some key. But after client called processEvents control is immediately returned to client. In such cases how will client know incase if some issue occurred. what are the best practice to tackle this? |
Can we use Mat-card with Anchor Tag? Posted: 15 May 2021 08:14 AM PDT I want to make mat-card to be clickable and when I hover over the mat-card I wanted to show link cursor. There are many cards when I click on one of the cards I want to navigate to another page. How Can I achieve this? Is it appropriate to use the following code in my template html. <a mat-card routerLink= ...> Buy </a> My first attempt was <div fxLayout="row rap"> <mat-card> <mat-card-content> <div> $100 </div> <div> 3000 ETB</div> </mat-card-content> </mat-card> <mat-card> .... </mat-card> </div> |
How to run a system command from VSCode extension Posted: 15 May 2021 08:14 AM PDT I am trying to create a simple VSCode extension to run a set of commands when I open a folder. Basically these commands will set up our development environment. I have started off creating the boilerplace and ran through the example that VSCode provided but I am not clear how to run system commands. Appreciate any help or point me to some documentation about this topic. |
Laravel5.3 maatwebsite/excel Read value from excel & insert into database Posted: 15 May 2021 08:15 AM PDT Here is my Excel data sheet type: Here is My Table Schema: Here is my method to import data: public function saveActivationInfoExcel(Request $request) { if($request->hasFile('import_file')){ $path = $request->file('import_file')->getRealPath(); $data = Excel::load($path, function($reader) {})->get(); if(!empty($data) && $data->count()){ foreach ($data->toArray() as $key => $value) { if(!empty($value)){ foreach ($value as $v) { $insert[] = [ 'mobile_no' =>$v['mobile_no'], 'model' => $v['model'], 'serial_1' => $v['serial_1'], 'serial_2' => $v['serial_2'], 'activation_date' => $v['activation_date'], ]; } } } dd($insert); if(!empty($insert)){ //ProductActivationInfo::insert($insert); return back()->with('success','Insert Record successfully.'); } } } return back()->with('error','Please Check your file, Something is wrong there.'); } Now my problem is, when I try to import data I got this dd($insert) error Illegal string offset 'mobile_no' 'serial_1' => '3.5194508009307E+14', 'serial_2' => '3.5194508009307E+14', 'activation_date' => object(Carbon), null) have a look both serial_1 & serial_2 showing different value rather then actual excel value. also activation_date value is null. would appreciate your valuable suggestion to solve this regarding reading data using "maatwebsite/excel" laravel library. |
Why on testing a Riak node 'riak-admin test' fails but 'curl -v http://127.0.0.1/8098/types/default/props' succeeds Posted: 15 May 2021 08:14 AM PDT I am setting up a riak cluster of five physical nodes. The other four are fine with all tests except one fails the admin-riak test. The cluster state on several riak-admin commands is shown below do-admin@DBNode1:~$ sudo riak-admin member-status =============== Membership ============================ Status Ring Pending Node ------------------------------------------------------------------------------- valid 20.3% -- 'riak@dbnode1.do.ug' valid 20.3% -- 'riak@dbnode2.do.ug' valid 20.3% -- 'riak@dbnode3.do.ug' valid 20.3% -- 'riak@dbnode4.do.ug' valid 18.8% -- 'riak@dbnode5.do.ug' ------------------------------------------------------------------------------- Valid:5 / Leaving:0 / Exiting:0 / Joining:0 / Down:0 dot-admin@DBNode1:~$ sudo riak-admin ring-status ================================== Claimant =================================== Claimant: 'riak@dbnode2.do.ug' Status: up Ring Ready: true ============================== Ownership Handoff ============================== No pending changes. ============================== Unreachable Nodes ============================== All nodes are up and reachable do-admin@DBNode1:~$ sudo riak-admin cluster status ---- Cluster Status ---- Ring ready: true +------------------------+------+-------+-----+-------+ | node |status| avail |ring |pending| +------------------------+------+-------+-----+-------+ | riak@dbnode1.do.ug |valid | up | 20.3| -- | | (C) riak@dbnode2.do.ug |valid | up | 20.3| -- | | riak@dbnode3.do.ug |valid | up | 20.3| -- | | riak@dbnode4.do.ug |valid | up | 20.3| -- | | riak@dbnode5.do.ug |valid | up | 18.8| -- | +------------------------+------+-------+-----+-------+ Key: (C) = Claimant; availability marked with '!' is unexpected do-admin@DBNode1:~$ curl -v http://dbnode1.dot.ug:8098/types/default/props * Hostname was NOT found in DNS cache * Trying 192.168.172.38... * Connected to dbnode1.dot.ug (192.168.172.38) port 8098 (#0) > GET /types/default/props HTTP/1.1 > User-Agent: curl/7.35.0 > Host: dbnode1.dotshule.ug:8098 > Accept: */* > < HTTP/1.1 200 OK < Vary: Accept-Encoding * Server MochiWeb/1.1 WebMachine/1.10.5 (jokes are better explained) is not blacklisted < Server: MochiWeb/1.1 WebMachine/1.10.5 (jokes are better explained) < Date: Sat, 17 Jan 2015 21:05:22 GMT < Content-Type: application/json < Content-Length: 428 < * Connection #0 to host dbnode1.dotshule.ug left intact {"props":{"allow_mult":false,"basic_quorum":false,"big_vclock":50,"chash_keyfun":{"mod":"riak_core_util","fun":"chash_std_keyfun"},"dvv_enabled":false,"dw":"quorum","last_write_wins":false,"linkfun":{"mod":"riak_kv_wm_link_walker","fun":"mapreduce_linkfun"},"n_val":3,"notfound_ok":true,"old_vclock":86400,"postcommit":[],"pr":0,"precommit":[],"pw":0,"r":"quorum","rw":"quorum","small_vclock":50,"w":"quorum","young_vclock":20}} dot-admin@DBNode1:~$ sudo riak-admin test Node 'riak@dbnode1.dot.ug ' is not reachable from 'riak_test@dbnode1.dot.ug'. After all those tests with the same results on all nodes except for the **riak-admin test ** which is like this on all other nodes. For node three dot-admin@DBNode3:~$ sudo riak-admin test Successfully completed 1 read/write cycle to 'riak@dbnode3.dotshule.ug' My doubt is whether this cluster is ready to used to store data because on this Basho website resource, they say you can use any of the methods to test whether the node is ready. They do not say that the node is still fine if one method success and the other fails. So I am stuck on whether to go ahead to use the cluster or not. Surprisingly this node has succeeded on all operations to join it in the cluster!! I have tried creating this node from scratch again but that has not helped! For any help, I will be glad. |
No comments:
Post a Comment