id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23526800
for example var abb =dat.Abbrivation ; A: You don't need jQuery. Just grab the object. var abb = dat[0].Abbrivation; jQuery is unfortunately a crutch for newer programmers. It is not necessarily good practice to turn everything into a jQuery function, especially if it isn't necessary at all. update dat, being an array, needs to have its first instance selected, which then has the Abbrivation property.
doc_23526801
D:\My First Directory D:\My Second Directory when I am pass this two argument in console program in C# like this : Program.exe D:\My First Directory D:\My Second Directory I access this this of output. args[0] : D:\My args[1] : First args[2] : Directory args[3] : D:\My args[4] : Second args[5] : Directory I want to this type of output : args[0] : D:\My First Directory args[1] : D:\My Second Directory A: The only way to do it is to pass the arguments inside double quotes, like this: Program.exe "D:\My First Directory" "D:\My Second Directory" There is no other simple way. Operating system just works like that. One string is one argument. You could do some wise mechanism though. I wouldn't do it, I would just put those directories in double quotes. But if I for some reason REALLY, REALLY had to do it, I'd do it like that: * *get all the arguments into one string *magically split this string into list (array) of strings, using regular expressions (looking for string like: "D:\", of course as a regular expression). But it could only work if you can only have directories in arguments and nothing else.
doc_23526802
There is an API call to verify receipts, but I cannot find one to cancel. I looked at apple developer doc but could not find it. Is there such an API? If not, what is the correct way to do this? A: Unfortunately, there is no API to cancel a subscription. User have to do it themselves in the manage subscription screen. For their convenience, you could provide a link to that screen in your app or via an email.
doc_23526803
It's both the .then part of the static addRoom within the class DOMManager Two videos in case it helps https://www.youtube.com/watch?v=69TMynpJDg8&t=326s https://www.youtube.com/watch?v=e5XkzrR2Et8&t=1s class House { constructor(name) { this.name = name; this.rooms = []; } addRoom(name, area) { this.rooms.push(new Room(name, area)); } } class Room { constructor(name, area) { this.name = name; this.area = area; } } class HouseService { static url = 'https://ancient-taiga-31359.herokuapp.com/api/houses'; static getAllHouses() { return $.get(this.url); } static getHouse(id) { return $.get(this.url + `/${id}`); } static createHouse(house) { return $.post(this.url, house); } static updateHouse(house) { return $.ajax({ url: this.url + `/${house._id}`, dataType: 'json', data: JSON.stringify(house), contentType: 'application/json', type: 'PUT' }) } static deleteHouse(id) { return $.ajax({ url: this.url + `/${id}`, type: 'DELETE' }); } } class DOMManager { static houses; static getAllHouses() { HouseService.getAllHouses().then(houses => this.render(houses)); } static createHouse(name) { HouseService.createHouse(new House(name)) .then(() => { return HouseService.getAllHouses(); }) .then((houses) => this.render(houses)); } static deleteHouse(id) { console.log(id) HouseService.deleteHouse(id) .then(() => { return HouseService.getAllHouses(); }) .then((houses) => this.render(houses)); } static addRoom(id) { for (let house of this.houses) { if (house._id == id) { house.rooms.push(new Room($(`#${house._id}-room-name`).val(), $(`#${house._id}-room-area`).val())) HouseService.updateHouse(house) //THIS THEN IS THE ISSUE .then(() => { console.log('Hello4' + id) return HouseService.getAllHouses(); }) console.log('Hello5') .then((houses) => this.render(houses)); } } } static deleteRoom(houseId, roomId) { for (let house of this.houses) { if (house._id == houseId) { for (let room of house.rooms) { if (room._id == roomId) { house.rooms.splice(house.room.indexOf(room), 1); HouseService.updateHouse(house) .then(() => { return HouseService.getAllHouses(); }) .then((houses) => this.render(houses)); } } } } } static render(houses) { this.houses = houses; $('#app').empty(); for (let house of houses) { $('#app').prepend( `<div id="${house._id}" class="card"> <div class="card-header"> <h2>${house.name}</h2> <button class="btn btn-danger" onclick="DOMManager.deleteHouse('${house._id}')">Delete</button> </div> <div <div class="card"> <div class="row"> <div class="col-sm"> <input type="text" id="${house._id}-room-name" class="form-control" placeholder="Room Name"> </div> <div class="col-sm"> <input type="text" id="${house._id}-room-area" class="form-control" placeholder="Room Area"> </div> </div> <button id="${house._id}-new-room" onclick="DOMManager.addRoom('${house._id}')" class="btn btn-primary form-control">Add</button> </div> </div> </div><br>` ); for (let room of house.rooms) { $(`#${house._id}`).find('.card-body').append( `<p> <span id="name-${room._id}"><strong>Name: </strong> ${room.name}</span> <span id="area-${room._id}"><strong>Area: </strong> ${room.area}</span> <button class="btn btn-danger" onclick="DOMManager.deleteRoom('${house._id}', '${room._id}')">Delete Rooms</button> ` ) } } } } $('#create-new-house').click(() => { DOMManager.createHouse($('#new-house-name').val()); $('#new-house-name').val(''); }); DOMManager.getAllHouses(); <!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>House App</title> <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css"> </head> <body class="container"> <div id="new-house" class="jumbotron"> <h2>New House</h2> <input type="text" id="new-house-name" class="form-control"> <br> <button id="create-new-house" class="btn btn-primary form-control">Create</button> </div> <div id="app"> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="index.js"></script> <script src="node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script> </body> </html>
doc_23526804
* *pickup *arrived *in_route_to_destination . . . and so on Since the database views dont propogate default values to the model, i am defining the values as follows def pickup self[:pickup] || true end def arrived self[:arrived] || true end def delivery self[:delivery] || true end There are 11 statuses and if i follow this way, i need to define 11 methods of the format def status_name self[:status_name] || true end Is there a way to optimise this? A: I'm not sure it's the best design to have separate columns for each status as opposed to a generic status column but I don't know your full requirements so maybe that works best. You can define them dynamically, though. STATUS_COLUMNS = %i(pickup arrived in_route_to_destination delivery) STATUS_COLUMNS.each do |method| define_method method do self[method] || true end end
doc_23526805
I did this but the problem is count value same for each row.so I want when user increase and decrease the count of row 0 the count 1 after that when user come to second-row count should start from 0 not be count 1 Please help me to resolve this issues??.I want to increase and decrease the count of each row. so According to count ,prize should be increased Row 1 Count 1,prize 100 =100 Row 2 Count 2,prize 200= 400 But In my case count always showing last count value.for each row count value should be start from 1 A: I don't know what you tried so far, but you can do something like this. holder.ivMinus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int quantity = Integer.parseInt(holder.tvItemQuantity.getText().toString()); if (quantity > 0) { quantity = quantity - 1; storeItem.setItemQuantity("" + quantity); holder.tvItemQuantity.setText(storeItem.getItemQuantity()); totoal = totoal * quantity; Gtotoal = Gtotoal - Integer.parseInt(storeItem.getItemPrice()); ; settotal.setTotal(" \u20B9 " + Gtotoal); } else { } } }); holder.ivPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int quantity = Integer.parseInt(holder.tvItemQuantity.getText().toString()); quantity = quantity + 1; storeItem.setItemQuantity("" + quantity); holder.tvItemQuantity.setText(storeItem.getItemQuantity()); Gtotoal = Gtotoal + Integer.parseInt(storeItem.getItemPrice()); settotal.setTotal(" \u20B9 "+ Gtotoal); } });
doc_23526806
C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD I got this result. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System EnableLUA REG_DWORD 0x0 But when I check UAC manually, I see the UAC is active. What is the reason of this? Can you help to solve this problem? Thank you. A: I solved this problem by restarting the computer after running script. C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
doc_23526807
$('.class').parent().hover( function() { $({ value: $(this).val() }).animate( .... ); ... }, function() { $({ value: $(this).val() }).animate( .... ); ... }); Unfortunately due to a plugin i use for creating a slider i have to use the .parent() selector, so i can not use .. $('.parent') -> $('.class', this) .. what i think it would solve it. I have three elements with the ".class"-class and they are all three animated whenever i hover one of them. further explanation: The html is only one thing: <input type="text" value="0" class="class" /> The Plugin creates a canvas above the input and the input is used as the value for the animated bar. It also creates a div wrapping around this two elements. Like so : <div> <canvas> <input ... > </div> I'm sure i can find a easy solution by using id's and writing it multiple times in the code with the id's as selector, but i hope for a more elegant way to solve this. Here the JSFiddle A: As long as you know that the <canvas> tag will always be created, why not just use the <canvas> tag as the selector to provide context? $('canvas').hover( function() { var that = $(this); $({ value: $(this).next() }).animate( ... progress: function() { that.next().val(Math.round(this.value)).trigger('change'); } ); }, function() { var that = $(this); $({ value: $(this).next().val() }).animate( ... progress: function() { that.next().val(Math.round(this.value)).trigger('change'); } ); }); NEW Working Fiddle A: Maybe try wrapping it in an event listener instead: $(function(){ $('.class').on('hover',function(){ $({value:$(this).parent().val()}).animate( ...) }) });
doc_23526808
Any ideas as to how to accomplish this functionality or if it is at all possible?
doc_23526809
This is my code: //THIS IS THE CODE FOR SKETCH.JS WITH THE PACMAN GAME.... var rocaImage; var foodImage; var grapeImage; var pacManImage; var roca; var myMaze; var arrayRocasMapa = []; var arrayComidaMapa = []; var arrayGrapesMapa = []; var myPacman; var font; var username = "Eduardo"; var song; //Pacman resources: http://www.classicgaming.cc/classics/pac-man/ function preload() { rocaImage = loadImage("images/roca.bmp"); foodImage = loadImage("images/food.png"); grapeImage = loadImage("images/grape.png"); pacManImage = loadImage("images/pac.png"); song = loadSound("assets/pacman_chomp.wav"); // font = loadFont('assets/SourceSansPro-Regular.otf'); } function setup() { createCanvas(COLUMNS * IMAGE_SIZE, ROWS * IMAGE_SIZE + HEIGHT_TEXT); roca = new Roca(200, 300); myMaze = new Maze(); for (var i = 0; i < myMaze.rows; i++) for (var j = 0; j < myMaze.columns; j++) { if (myMaze.mapa[i][j] == 0) { arrayRocasMapa.push(new Roca(j * IMAGE_SIZE, i * IMAGE_SIZE)); } else if (myMaze.mapa[i][j] == 1) { arrayComidaMapa.push(new Food(j * IMAGE_SIZE, i * IMAGE_SIZE)); } else if (myMaze.mapa[i][j] == 2) { arrayGrapesMapa.push(new Grapes(j * IMAGE_SIZE, i * IMAGE_SIZE)); } else if (myMaze.mapa[i][j] == 3) { myPacman = new Pacman(j * IMAGE_SIZE, i * IMAGE_SIZE); } } // Set text characteristics textFont("monospace"); //https://developer.mozilla.org/en-US/docs/Learn/CSS/Styling_text/Fundamentals#Web_safe_fonts textSize(14); textAlign(LEFT, CENTER); // Constant:horizontal alignment, vertical aligntment either LEFT, CENTER, or RIGHT textStyle(NORMAL); //Italic o Bold } function draw() { background(0); // roca.show(); //with i i count the rows, with j the columns for (var i = 0; i < arrayRocasMapa.length; i++) { console.log("Imprimo una roca:" + i); arrayRocasMapa[i].show(); } i = 0; for (i = 0; i < arrayComidaMapa.length; i++) { console.log("Imprimo una bola de comida:" + i); arrayComidaMapa[i].show(); } i = 0; for (i = 0; i < arrayGrapesMapa.length; i++) { console.log("Imprimo una uva de poder:" + i); arrayGrapesMapa[i].show(); } myPacman.show(); for (i = 0; i < arrayComidaMapa.length; i++) { console.log("Compruebo si hay comida en la :" + i); if (myPacman.eatFood(arrayComidaMapa[i])) { arrayComidaMapa.splice(i, 1); } } for (i = 0; i < arrayGrapesMapa.length; i++) { if (myPacman.eatGrapes(arrayGrapesMapa[i])) { arrayGrapesMapa.splice(i, 1); } } for (i = 0; i < arrayRocasMapa.length; i++) { if (myPacman.eatRock(arrayRocasMapa[i])) { //arrayRocaMapa.splice(i,1); } } drawtext(); // addSound(); if (arrayGrapesMapa.length == 0 && arrayComidaMapa.length == 0) { alert("Victory !!!"); remove(); } if (myPacman.lives == 0) { alert("Defeat !!!"); remove(); } } function addSound() { if (song.isPlaying()) { // .isPlaying() returns a boolean } else { song.play(); // playback will resume from the pause position } } function drawtext() { // textSize(18); var textCoordY = ROWS * IMAGE_SIZE + HEIGHT_TEXT / 2; var txtUser = "User :" + username; var txtScore = "Score :" + myPacman.score; var txtLives = "Lives :" + myPacman.lives; fill('white'); text(txtUser, 30, textCoordY); var cWidthUser = textWidth(txtUser) + 10 + 30; fill('blue'); text(txtScore, cWidthUser, textCoordY); cWidthScore = textWidth(txtScore) + 10; fill('red'); text(txtLives, cWidthUser + cWidthScore, textCoordY); // /* // textSize(24); // text('User', 30, ROWS*32+HEIGHT_TEXT/2); // fill(0, 102, 153); // text('Score', 100, ROWS*32+HEIGHT_TEXT/2); // fill(0, 102, 153, 51); // fill(0); // text('Lives', 250, ROWS*32+HEIGHT_TEXT/2); } function mousePressed() { if (song.isPlaying()) { // .isPlaying() returns a boolean song.pause(); background(255, 0, 0); } else { song.play(); // playback will resume from the pause position background(0, 255, 0); } } function keyPressed() { // console.log("Algo pasa nenn"); if (keyCode === 68 || keyCode === RIGHT_ARROW) //Letra d { console.log("Estoy dentro de mover derecha"); myPacman.moveRight(); //console.log("Estoy dentro de mover derecha"); } if (keyCode === 65 || keyCode === LEFT_ARROW) // Letra a { console.log("Estoy dentro de mover izquierda"); myPacman.moveLeft(); //console.log("Estoy dentro de mover derecha"); } if (keyCode === 87 || keyCode === UP_ARROW) // Letra W { console.log("Estoy dentro de mover arriba"); myPacman.moveUp(); //console.log("Estoy dentro de mover derecha"); } if (keyCode === 88 || keyCode === DOWN_ARROW) // Letra X { console.log("Estoy dentro de mover abajo"); myPacman.moveDown(); //console.log("Estoy dentro de mover derecha"); } } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Pacman</title> <link rel="icon" href="images/ghost.png" /> <link rel="stylesheet" type="text/css" href="css/style.css" /> </head> <body> <script src="library/p5.js" type="text/javascript"></script> <script src="library/addons/p5.dom.js" type="text/javascript"></script> <script src="library/addons/p5.sound.js" type="text/javascript"></script> <!-- <script src="sketch.js" type="text/javascript"></script> --> <script src="roca.js" type="text/javascript"></script> <script src="maze.js" type="text/javascript"></script> <script src="food.js" type="text/javascript"></script> <script src="grapes.js" type="text/javascript"></script> <script src="pacman.js" type="text/javascript"></script> <script> function startGame() { //HERE I WANT TO LAUNCH SKETCH.JS BUT I CANT I HAVE TESTED MANY DIFFERENT ORDERS document.write("<script src='sketch.js' type='text\/javascript'><\/script>"); } </script> <header> <h1> Pacman Game by Eduardo</h1> </header> <img src="./images/splash-image.jpg" alt="Splash image of Pacman" /> <nav class="topnav"> <a href="/">Settings</a> <a href="">Start Game</a> <button onclick="startGame()" class="topnav"> Start Game</button> <a href="">Credits</a> </nav> </body> </html> So if i comment ( like in the code) the loading of the script sketch.js i cant go to my sketch.js where i load the maze and the game background… But i have tried many things ( document.write, innerHTML, etc…) i just want to load sketch when i click on Button startGame ( so the function startGame would be launched)… If i delete the comments, and use the script, it works ok, but i want to control when to launch sketch.js ( when i press the button Start Game and not before) If you know of anything easier would be nice… Also i have another doubt… i want to print some text like scores, lives and time remaining… do you use another canvas to put text on it ( perhaps in a side of the screen or in the bottom), o in the same canvas you make room to have enough space to write ?? Thanks A: You could store whether the game is started in a variable at the top of your sketch: var started = false; function draw(){ if(started){ // draw your game } } function mousePressed(){ started = true; } You could set started equal to true when you press the button. Or you could look into instance mode which allows you to load a sketch on the fly. You can read more about instance mode here. Also i have another doubt… i want to print some text like scores, lives and time remaining… do you use another canvas to put text on it ( perhaps in a side of the screen or in the bottom), o in the same canvas you make room to have enough space to write ?? Either approach is fine. It's completely up to you. You could also modify the webpage and print the score there. The P5.dom library could come in handy for this.
doc_23526810
Time::DATE_FORMATS[:db_usec] = '%Y-%m-%d %H:%M:%S.%6N' But with this format the time is formated with local time zone. I have to change the time in UTC first. Post.created_at.utc.to_s(:db_usec) How can I write a DATE_FORMATS like :db that formats the time in UTC? A: You can easily change it by referring to the Rails api link. Time::DATE_FORMATS[:db_usec] = ->(time) { time.utc.strftime('%Y-%m-%d %H:%M:%S.%6N') }
doc_23526811
* *I have defined the classes as below. *I have used dagger with Retrofit here What I am trying to do:: I am trying to catch the OfflineException in the request below how to catch it in Main Activity properly. RequestInterceptor.java public class RequestInterceptor implements Interceptor { ConnectivityManager connectivityManager; Application mApplication; @Inject public RequestInterceptor(Application mApplication) { this.mApplication = mApplication; connectivityManager = (ConnectivityManager) mApplication.getSystemService(Context.CONNECTIVITY_SERVICE); } @Override public Response intercept(Chain chain) throws IOException { if (isConnected()) { throw new OfflineException(); } Request.Builder r = chain.request().newBuilder(); return chain.proceed(r.build()); } protected boolean isConnected() { NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnectedOrConnecting(); } public class OfflineException extends IOException { @Override public String getMessage() { return mApplication.getResources().getString(R.string.app_no_connectivity); } } } NetModule.java import android.app.Application; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import commons.LinksAndKeys; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import retrofitDagger.retrofitUtils.RequestInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; @Module public class NetModule { String mBaseUrl; Application mApplication; // Constructor needs one parameter to instantiate. public NetModule(String baseUrl, Application application) { this.mBaseUrl = baseUrl; this.mApplication = application; } // Dagger will only look for methods annotated with @Provides @Provides @Singleton // Application reference must come from AppModule.class SharedPreferences providesSharedPreferences(Application application) { return PreferenceManager.getDefaultSharedPreferences(application); } @Provides @Singleton Application providesApplication() { return mApplication; } @Provides @Singleton Cache provideOkHttpCache(Application application) { int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(application.getCacheDir(), cacheSize); return cache; } @Provides @Singleton Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); } @Provides @Singleton OkHttpClient provideOkHttpClient(Cache cache) { OkHttpClient.Builder client = new OkHttpClient.Builder(); client.cache(cache); client.addInterceptor(new RequestInterceptor(mApplication)); client.readTimeout(LinksAndKeys.READ_TIMEOUT, TimeUnit.SECONDS); client.connectTimeout(LinksAndKeys.CONNECTION_TIMEOUT, TimeUnit.SECONDS); return client.build(); } @Provides @Singleton Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(mBaseUrl) .client(okHttpClient) .build(); return retrofit; } } MainActivity.java public class MainActivity extends AppCompatActivity { @Inject Retrofit retrofit; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ((App) getApplication()).getNetComponent().inject(this); //Create textview and findViewByID textView = (TextView) findViewById(R.id.textview_post); //Create a retrofit call object Call<List<Post>> posts = retrofit.create(Restapi.class).getPosts(); //Enque the call posts.enqueue(new Callback<List<Post>>() { @Override public void onResponse(Call<List<Post>> call, Response<List<Post>> response) { //Set the response to the textview textView.setText(response.body().get(0).getBody()); } @Override public void onFailure(Call<List<Post>> call, Throwable t) { //Set the error to the textview textView.setText(t.toString()); } }); } } A: As I know, there is no internet connection the RetrofitError contains a ConnectionException as the cause. public class RetrofitErrorHandler implements ErrorHandler { @Override public Throwable handleError(RetrofitError cause) { if (cause.isNetworkError()) { if (cause.getCause() instanceof SocketTimeoutException) { /* your code here*/ return new MyConnectionTimeoutException(); } else { /* your code here*/ return new MyNoConnectionException(); } } else { //Do whatever you want to do if there is not a network error. } } } Or you can create a custom Retrofit client that checks for connectivity before executing a request and throws an exception. public class ConnectivityCheck implements Client { Logger log = LoggerFactory.getLogger(ConnectivityCheck.class); public ConnectivityCheck (Client wrappedClient, NetworkConnectivityManager ncm) { this.wrappedClient = wrappedClient; this.ncm = ncm; } Client wrappedClient; private NetworkConnectivityManager ncm; @Override public Response execute(Request request) throws IOException { if (!ncm.isConnected()) { log.debug("No connectivity %s ", request); throw new NoConnectivityException("No connectivity"); } return wrappedClient.execute(request); } } and then use it when configuring RestAdapter RestAdapter.Builder().setEndpoint(serverHost) .setClient(new ConnectivityCheck(new OkHttpClient(), ...)) A: As far as I know, I don't think Retrofit supports 'connectivity checking in call time' and I don't think that is exactly what you want. Try to check connectivity before your call, for example, private void sendData() { if( isConnected ) { switch(call) { case "userSignIn": Call ! break; ... } } Maybe you can check this solution too
doc_23526812
Want to pass correlation Id(unique id) to the outbound wcf service. I'm trying to add behavior for the correlationid. With that if it'll solve the purpose. What is the way to achieve this
doc_23526813
Error Stack: 02-27 11:41:16.046: E/AndroidRuntime(5413): FATAL EXCEPTION: main 02-27 11:41:16.046: E/AndroidRuntime(5413): java.lang.ArrayIndexOutOfBoundsException 02-27 11:41:16.046: E/AndroidRuntime(5413): at com.TestFace.FaceDetect.DrawView.onTouchEvent(DrawView.java:132) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.view.View.dispatchTouchEvent(View.java:3766) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:936) 02-27 11:41:16.046: E/AndroidRuntime(5413): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1676) 02-27 11:41:16.046: E/AndroidRuntime(5413): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1112) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.app.Activity.dispatchTouchEvent(Activity.java:2086) 02-27 11:41:16.046: E/AndroidRuntime(5413): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1660) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.view.ViewRoot.handleMessage(ViewRoot.java:1785) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.os.Handler.dispatchMessage(Handler.java:99) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.os.Looper.loop(Looper.java:123) 02-27 11:41:16.046: E/AndroidRuntime(5413): at android.app.ActivityThread.main(ActivityThread.java:4627) 02-27 11:41:16.046: E/AndroidRuntime(5413): at java.lang.reflect.Method.invokeNative(Native Method) 02-27 11:41:16.046: E/AndroidRuntime(5413): at java.lang.reflect.Method.invoke(Method.java:521) 02-27 11:41:16.046: E/AndroidRuntime(5413): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 02-27 11:41:16.046: E/AndroidRuntime(5413): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 02-27 11:41:16.046: E/AndroidRuntime(5413): at dalvik.system.NativeStart.main(Native Method) DrawView.java: package com.TestFace.FaceDetect; import java.io.IOException; import java.net.MalformedURLException; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import android.view.View; import com.TestFace.FaceDetect.Util.ResultPack; public class DrawView extends View { private ColorBall[] colorballs = new ColorBall[3]; // array that holds the balls private int balID = 0; // variable to know what ball is being dragged ResultPack result = ResultPack.getSingletonObject(); Bitmap myBitmap,myBitmap_Circle; int width, height; public DrawView(Context context) { super(context); setFocusable(true); //necessary for getting the touch events // setting the start point for the balls Point point1 = new Point(); point1.x = (int)result.getEyeLeftX()+50; point1.y = (int)result.getEyeLeftY()+25; Point point2 = new Point(); point2.x = (int)result.getEyeRightX()+50; point2.y = (int)result.getEyeRightY()+25; Point point3 = new Point(); point3.x = (int)result.getMouthCenterX()+50; point3.y = (int)result.getMouthCenterY()+25; Drawable d=null; try { d = drawable_from_url(result.getImgUrl(), "Image Url"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } myBitmap=((BitmapDrawable)d).getBitmap(); myBitmap_Circle = BitmapFactory.decodeResource(getResources(), R.drawable.circle1); // declare each ball with the ColorBall class colorballs[0] = new ColorBall(context,myBitmap_Circle, point1); colorballs[1] = new ColorBall(context,myBitmap_Circle, point2); colorballs[2] = new ColorBall(context,myBitmap_Circle, point3); width=myBitmap.getWidth(); height=myBitmap.getHeight(); } Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException { return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name); } // the method that draws the balls @Override protected void onDraw(Canvas canvas) { //canvas.drawColor(0xFFCCCCCC); //if you want another background color canvas.drawBitmap(myBitmap, 0,0, null); //draw the balls on the canvas for (ColorBall ball : colorballs) { canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null); } } // events when touching the screen public boolean onTouchEvent(MotionEvent event) { int eventaction = event.getAction(); int X = (int)event.getX(); int Y = (int)event.getY(); switch (eventaction ) { case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball balID = 0; for (int i=0;i<colorballs.length;i++) { // check if inside the bounds of the ball (circle) // get the center for the ball int centerX = colorballs[i].getX() + 25; int centerY = colorballs[i].getY() + 25; // calculate the radius from the touch to the center of the ball double radCircle = Math.sqrt( (double) (((centerX-X)*(centerX-X)) + (centerY-Y)*(centerY-Y))); System.out.println("The Rad Circle:"+radCircle); // if the radius is smaller then 23 (radius of a ball is 22), then it must be on the ball if (radCircle < 23){ balID = colorballs[i].getID(); } // check all the bounds of the ball (square) //if (X > ball.getX() && X < ball.getX()+50 && Y > ball.getY() && Y < ball.getY()+50){ // balID = ball.getID(); // break; //} } break; case MotionEvent.ACTION_MOVE: // touch drag with the ball // move the balls the same as the finger if (balID > 0) { colorballs[balID-1].setX(X-25); colorballs[balID-1].setY(Y-25); } break; case MotionEvent.ACTION_UP: // touch drop - just do things here after dropping break; } // redraw the canvas invalidate(); return true; } } ColorBall.java: package com.TestFace.FaceDetect; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; public class ColorBall { private Bitmap img; // the image of the ball private int coordX = 0; // the x coordinate at the canvas private int coordY = 0; // the y coordinate at the canvas private int id; // gives every ball his own id, for now not necessary private static int count = 1; private boolean goRight = true; private boolean goDown = true; public ColorBall(Context context, Bitmap drawable) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; //img = BitmapFactory.decodeResource(context.getResources(), drawable); img = drawable; id=count; count++; } public ColorBall(Context context, Bitmap drawable, Point point) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; //img = BitmapFactory.decodeResource(context.getResources(), drawable); img = drawable; id=count; count++; coordX= point.x; coordY = point.y; } public static int getCount() { return count; } void setX(int newValue) { coordX = newValue; } public int getX() { return coordX; } void setY(int newValue) { coordY = newValue; } public int getY() { return coordY; } public int getID() { return id; } public Bitmap getBitmap() { return img; } public void moveBall(int goX, int goY) { // check the borders, and set the direction if a border has reached if (coordX > 270){ goRight = false; } if (coordX < 0){ goRight = true; } if (coordY > 400){ goDown = false; } if (coordY < 0){ goDown = true; } // move the x and y if (goRight){ coordX += goX; }else { coordX -= goX; } if (goDown){ coordY += goY; }else { coordY -= goY; } } } A: The problem is that you generate id for your ColorBall and then try to use this id as an index of colorballs array: private static int count = 1; public ColorBall(Context context, Bitmap drawable) { ... id=count; count++; } and: protected void onDraw(Canvas canvas) { ... case MotionEvent.ACTION_MOVE: // touch drag with the ball // move the balls the same as the finger if (balID > 0) { colorballs[balID-1].setX(X-25); colorballs[balID-1].setY(Y-25); } break; ... } Which evidently is wrong. If it is id of the ColorBall that you want to refer ColorBall objects by, then consider using other types of collections to hold a list of ColorBall objects, i.e. HashMap<Integer, ColorBall>, otherwise use the index of element within the array to refer to certain ColorBall object.
doc_23526814
Error: Cannot find module 'worker_threads' ## Heading ##at Function.Module._resolveFilename (internal/modules cjs/loader.js:636:15) at Function.Module._load (internal/modules/cjs/loader.js:562:25) at Module.require (internal/modules/cjs/loader.js:692:17) at require (internal/modules/cjs/helpers.js:25:18) at /home/erichuang2005/substrate-node-template/substrate-front-end-template/.yarn/releases/yarn-berry.cjs:289:2658 A: I'm not sure about your exact error message but I also had a problem with yarn install which was solved by using a different version of node. I had a problem with version 17. Version 16 worked for me.
doc_23526815
I used localhost url on frontend when developing the project on local. http://localhost:5000 So, Request URL was http://localhost:5000/api/signup. I deployed the project on AWS lightsail,then I got 2 ip addresses.(public ip address, private ip address). How can I change this url(http://localhost:5000) for the correct request?
doc_23526816
/usr/share/vagrant/gems/gems/vagrant-2.1.2/lib/vagrant/util/safe_exec.rb:39: in `exec': : Permission denied - /home/username/bin/sshPermission denied - /home/username/bin/ssh ( (Errno::EACCESErrno::EACCES) The doc says: Vagrant will attempt to use the local SSH client installed on the host machine. However, which ssh correctly results in: /usr/bin/ssh. So why vagrant doesn't use it ? The directory! /home/username/bin/ssh was included in the PATH env when the box was created and vagrant seems to have stored this information somewhere. Removing the directory from PATH didn't help. Only when I rename or remove the directory vagrant ssh does work. Can anyone tell me where vagrant stored the wrong info ? Edit: The Vagrantfile is nearly empty, only config.vm.box contained... A: Guess I found the reason - seems to be a bug or strange behavior of the vagrant version 2.1.2 that I use: I still had directory /home/username/bin in the PATH env. Vagrant seems to list all entries in all directories included in PATH to look for ssh and finds subdirectory /home/username/bin/ssh not realizing that this is a directory ... After removing /home/username/bin the command vagrant ssh works as expected. So unless vagrant is improved I have to permanently rename my /home/username/bin/ssh directory ...
doc_23526817
BYTEORDER LITTLE ENDIAN BYTEORDERMARK NOCHECK Which means the file will be converted to little endian format (system format), here the sqlldr loads the data into table. somehow i try to read the data from file directly through vi though its unicode format is different hence i couldn't read the same. I tried searching the commands to convert the normal file and i had came over iconv commads and i used like below iconv -c -t UTF-8LE filename.dat > output.txt but it doesnot give output as expected.
doc_23526818
Error: could not find function "tokens". But I can use, for example, "tokenize". My code is: train.tokens <- tokens(train$Text, what = "word", remove_numbers = TRUE, remove_punct = TRUE,remove_symbols = TRUE, remove_hyphens = TRUE). As a side note, when I try to automatically update the quanteda package, it says that I have the 0.9.8.3 version and that the newest available is 0.9.8.5. After it gets updated, nothing happens. Thank you! A: You need to make sure you have a current version of quanteda and the packages that it imports. Then this will work fine: > quanteda::tokens("This is a test") tokens from 1 document. text1 : [1] "This" "is" "a" "test" > packageVersion("quanteda") [1] ‘0.99.22’
doc_23526819
//vuex import {modifyResults, updateResults} from './api'; const actions = { async modifyResults({ dispatch }) { try { // waiting for ModifyResults to finish entirely but after // functionOne from api folder is finished // it executes updateResults from here and then executes // functionTwo from api folder await modifyResults(); dispatch('updateResults'); } catch (error) { // catch errors } finally { // loading variable set to false } }, async updateResults({ dispatch }, ) { try { const { sources } = await updateResults(); dispatch('setItems', sources); } //blah blah }, } // api.js export const modifyResults = async () => { await functionOne({someApi}, async functionTwo(status, resposne) => { const { data } = await api.post(//blah blah); return data } ) }, export const updateResults = async () => { // blah return result }, So basically what happens is this is the order in which these functions are executed: 1- functionOne 2- updateResults 3- functionTwo whereas I want this order: 1- functionOne 2- functionTwo 3- updateResults
doc_23526820
Is there a way to trigger an RDP or some GUI style user session to become active in a headless manner? If not, then is there a different way to execute my application, where the interactive GUI is available with SSH or other means of headless connection when there is no active user signed in? The Windows VMs have OpenSSH server running for connections. A: This question actually solved the other half of the puzzle for me, namely how to get SSH connections to use the interactive session. Here's how to keep an active interactive session open at all times. Note that depending on your use case you might explicitly need a multi-session windows installation, which is a different VM image in Azure for example. * *Have the user you want these commands to run in log on automatically when windows boots. https://learn.microsoft.com/en-us/troubleshoot/windows-server/user-profiles-and-logon/turn-on-automatic-logon *Create a .bat file with the following contents somewhere (for me it's just on C:) tscon 1 /dest:console *In task scheduler, create a task that runs this bat file whenever a remote user disconnects. Point 2-3 are not necessary if you never RDP into the autologon user. Whenever you RDP to this user, the console session moves from the autologon session to your RDP session, and this script just reattaches the console session back when you disconnect. This way, that user always has the console attached and thus has GUI available.
doc_23526821
E.g.: FROM daggerok/jboss-eap-6.4:6.4.22-alpine RUN sudo apk add --update --no-cache nfs-utils RUN sudo apk add --update --no-cache openrc RUN sudo rc-update add nfsmount RUN sudo mount -t nfs nfs.local:FILE_SHARE /mnt A: Allowing a container to perform a filesystem mount would be a security vulnerability, allowing a container escape to the host. You cannot do this at build time in the Dockerfile. Instead you should configure the container with a volume mount. Support for this was added earlier this year.
doc_23526822
ROOT > DOMAIN ROOT FOLDER > PHP MKDIR ROOT > IMAGE FOLDER > MKDIR HERE I need the php in the 'domain root folder' to create a directory within the 'image folder'. Any help? A: You can usually do something like this: mkdir('../images/newfolder'); You may have to add more ../../ on to the front of this, depending on where you are running the script from exactly. Each ../ moves you up another level, so it seems like just one would work here given your example, but you have to be sure you are where you think you are. A: You could also use absolute path in your php-script. mkdir('/root/images/new_folder'); Make sure that your web-server has permissions for writing to specific folder. A: I usally work from the directory my current script is located in and maneuver my way to the desired location from there. Works fine as long as you don't move you script. In addition, it will be easier to keep track of where everything is relative to the script. You can get the current path with: $path = dirname(__FILE__); Then appending ../ to go deeper etc.
doc_23526823
My question is as follows: I have "images", all of the same dimensions, which in some sense correspond to different phases of a target image. And I'd like to rebuild that full-blown image with tf functionality. This turns out to be much less simple than I originally expected and I'd be very grateful for any help! A more detailed exposition follows: In numpy, one easily interleaves images via simple assignment - import numpy as np im = np.random.random((1, 8, 8, 2)) phased_im_01 = im[:, ::2, 1::2, :] phased_im_00 = im[:, ::2, ::2, :] phased_im_10 = im[:, 1::2, ::2, :] phased_im_11 = im[:, 1::2, 1::2, :] rebuild_im = np.zeros((1, 8, 8, 2)) rebuild_im[:, ::2, ::2, :] = phased_im_00 rebuild_im[:, ::2, 1::2, :] = phased_im_01 rebuild_im[:, 1::2, ::2, :] = phased_im_10 rebuild_im[:, 1::2, 1::2, :] = phased_im_11 print(np.all(rebuild_im == im)) But as known, assignment is a no-go in tf, and one usually uses things like tf.concat coupled with tf.reshape (for very simple cases) or tf.scatter_nd (for more complicated cases). I was unsuccessful in implementing the equivalent of the above numpy-functionality using any of the many things I tried (like permuting the tensor to have the width dimension first, trying to scatter_nd, and permuting back, a method I've successfully used before for other problems), or any solution on SO (like stacking and reshaping oneself to death). Just to be clear, my actual use-case has an unknown batch-size, thousands of channels, and 4 phases in each image dimension. But I just need a working solution for the simple toy example above; generalization is on me ;-) Thanks to any helpers out there, (and sorry I can only describe my efforts and not show them. They're just a mess of unsuccessful mistakes degrading into horrible trial-and-error code snippets until giving up and coming here for some help anyway, so no major loss). Clarifications can be added on demand. A: To reproduce the numpy example in TensorFlow, please try depth_to_space: import tensorflow as tf im = tf.random_normal((1, 8, 8, 2)) phased_im_01 = im[:, ::2, 1::2, :] phased_im_00 = im[:, ::2, ::2, :] phased_im_10 = im[:, 1::2, ::2, :] phased_im_11 = im[:, 1::2, 1::2, :] phases = tf.concat( (phased_im_00, phased_im_01, phased_im_10, phased_im_11), axis=3) rebuild_im = tf.nn.depth_to_space(phases, block_size=2, data_format='NHWC') dif = tf.reduce_sum(rebuild_im - im) # 0.0 As kindly suggested by ShlomiF, the more general example is: import numpy as np import tensorflow as tf tf.enable_eager_execution() num_of_channels = 20 h = w = 256 num_of_phases = 4 im = np.random.random((1, h, w, num_of_channels)) phase_ims = [] for i in range(num_of_phases): for j in range(num_of_phases): phase_ims.append(im[:, i::num_of_phases, j::num_of_phases, :]) all_phases = tf.concat(phase_ims, axis=3) rebuild_im = tf.depth_to_space(all_phases, block_size=num_of_phases, data_format='NHWC') diff = tf.reduce_sum(rebuild_im - im) print(np.asarray(diff)) # --> 0.0 As far as I know, the idea of depth_to_space, or periodic shuffling, came from this paper. You may find more details and visualization there.
doc_23526824
import math import random random.seed() n = 10000 for i in range(n): x = random.random() y = random.random() z = (x,y) if x**2+y**2 <= 1: print z else: del z So far, I am able to generate all of the points I need, but what I would like to get is the number of points that are produced when running the script for use in a later calculation. I'm not looking for incredibly precise results, just a good enough estimate. Any suggestions would be greatly appreciated. A: Not sure if this is what you're looking for, but you can run enumerate on range and get the position in your iteration: In [1]: for index, i in enumerate(xrange(10, 15)): ...: print index + 1, i ...: ...: 1 10 2 11 3 12 4 13 5 14 In this case, index + 1 would represent the current point being created (index itself would be the total number of points created at the beginning of a given iteration). Also, if you are using Python 2.x, xrange is generally better for these sorts of iterations as it does not load the entire list into memory but rather accesses it on an as-needed basis. A: If you're doing any kind of heavy duty numerical calculation, considering learning numpy. Your problem is essentially a one-linear with a numpy setup: import numpy as np N = 10000 pts = np.random.random((N,2)) # Select the points according to your condition idx = (pts**2).sum(axis=1) < 1.0 print pts[idx], idx.sum() Giving: [[ 0.61255615 0.44319463] [ 0.48214768 0.69960483] [ 0.04735956 0.18509277] ..., [ 0.37543094 0.2858077 ] [ 0.43304577 0.45903071] [ 0.30838206 0.45977162]], 7854 The last number is count of the number of events that counted, i.e. the count of the points whose radius is less than one. A: Just add hits variable before the loop, initialize it to 0 and inside your if statement increment hits by one. Finally you can calculate PI value using hits and n. import math import random random.seed() n = 10000 hits = 0 # initialize hits with 0 for i in range(n): x = random.random() y = random.random() z = (x,y) if x**2+y**2 <= 1: hits += 1 else: del z # use hits and n to compute PI
doc_23526825
After constructing obj1 = myClass(12) and calling class function obj1.printInfo(), I am getting an error - AttributeError: type object 'myClass' has no attribute 'arg1' What might be the source of the problem ?? class myClass(object): def __init__(self, arg1, arg2 = 0): self.arg1 = arg1 self.arg2 = arg2 def printInfo (self): print myClass.arg1, myClass.arg2 obj1 = myClass(12) obj1.printInfo() Thanks ! A: You want to use replace the body of printInfo(self) with: def printInfo(self): print self.arg1, self.arg2 The use of self here is not to specify the scope, as it is sometimes used in Java (MyClass.this) or in PHP. In this function, self is actcually the object that contains arg1 and arg2. Python is very explicit in this manner. In your previous method, you assigned arg1 and arg2 for self, so you should expect to get arg1 and arg2 back off of self. With regard to your second question, if you want a "class" function (i.e. a static method), then you still need a reference to your obj1 to access its properties. For example: class MyClass(object): def __init__(self, arg1, arg2 = 0): self.arg1 = arg1 self.arg2 = arg2 @staticmethod def printInfo(obj): print obj.arg1, obj.arg2 obj1 = MyClass(12) MyClass.printInfo(obj1) Also be sure to read PEP8 when you get a chance :) A: Brain fart, eh? Switch myClass.arg1 to self.arg1: def printInfo (self): print self.arg1, self.arg2 A: You can do it like this: def f1(arg1, arg2): print arg1, arg2 class myClass(object): def __init__(self, arg1, arg2 = 0): self.arg1 = arg1 self.arg2 = arg2 def printInfo (self): f1(self.arg1, self.arg2) obj1 = myClass(12) obj1.printInfo()
doc_23526826
<h1 id="testpos">HEADLINE</h1> <form method="post" action="#testpos"> However, since my horizontal menu bar is always fixed on top, I need it to scroll to the #testpos div + height of the menu bar (I know the height) Any way to do this?
doc_23526827
I tried to mix the tf layer inside my other keras layers. input = Input(shape=state_shape) conv = Conv2D(64, (6, 6), strides=(1, 1), activation='relu')(input) spatial_softmax = tf.contrib.layers.spatial_softmax(conv, name='spatial_softmax', data_format='NHWC') fc = Dense(128, activation='relu')(spatial_softmax) fc = Dense(128, activation='relu')(fc) output = Dense(action_size, activation='softmax')(fc) Model(inputs=input, outputs=output) But when I run the code I get the following error AttributeError: 'Tensor' object has no attribute '_keras_history' Any idea? Thanks! Edit: It's not the same question as here, I am asking for a layer with trainable weights and not a deterministic layer. Do the gradients will backprop to the layer ? A: I believe you would need to put that inside a Lambda layer: spatial_softmax = Lambda(lambda x: spatial_softmax(x, name='spatial_softmax', data_format='NHWC'))(conv)
doc_23526828
@foreach($image_data as $image) <a href="#" data-toggle="modal" data-target="#{{$image->image_id}}"> <img src="{{asset('public/user_images/')}}/{{$image->image_name}}"> </a> <div class="modal fade" id="{{$image->image_id}}" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span></button> <div class="modal-body"> <img src="{{asset('public/user_images/')}}/{{$image->image_name}}"> </div> </div> </div> </div> @endforeach What javascript or something else should I use to pop up this model ? A: $('.buttonClass').on('click', function(){ $('#modalID').fadeIn(); }); modalID has to be determined by a data-attribute that you can give to your buttons. For example <button type="button" class="open" data-dismiss="modal" data-id={{$image->image_id}}> And then in JavaScript add $('.buttonClass').on('click', function(){ let modalID = '#' + $(this).data('id'); $(modalId).fadeIn(); }); A: Add class="modal-open" to your as jQuery method $('.modal-open').on('click', function() { $( '#'+$(this).data('target') ).show(); }) Typing from my head so there could be typos. If the as and .modals are added dynamically then: $(this).on('click','.modal-open', function() { ...
doc_23526829
My goal is to create a new type of product (different from Coffee and Brewer) Here it says that we can create our own type of page and tranform them as product via the ecommerce tab: https://docs.kentico.com/k11/e-commerce-features/configuring-your-store/configuring-product-page-types What I should see: What I see: (no ecommerce tab on the left) I checked on the content module and I see a macro for a field called "Visible condition", is it why the tab is hidden ? I'm connected as "administrator" so it should not be a problem of permissions. Do you know how to make it visible ? A: You are missing lots of tabs on the left like Fields, Layout, Alternative forms, Search as well. Make sure you macro signature is correct by going to System app > macro signature to resign them. Also make sure your hashsalt is the same in both Admin and MVC web.config.
doc_23526830
After my first attempt at coding this solution, my localStorage entry looked like this: 616845040,796177849,848184043,1133088406,1205053317,1478518197,1525440546,1686606993,1753347541,1908577591,2056496592,-864967541,-1185668678,-835401591,-1017499054,-559563441,-1842092814,-1069291933,-1887162563 19 hashes, 210 bytes of data. A little later, I revisited the code. Instead of just dumping the integers as decimal strings, I converted them into actual binary data. In other words, each hash is now a string of four characters in length representing the binary value of the integer. My localStorage entry now looks like this: $ÄNð/tµ¹2BëCGÓ§X eµZì`"dhõÕqÂ7z¥Ðᅩq¤ᄍT!ºᅫ4ÈᅢZ2R￞¥½Oメ3äò￀Cæcマ/= 19 hashes, 76 bytes of data (There's some non-printable characters in there) That's a savings of 63.8%. Now, I am well aware that localStorage provides, by default, 5MB of storage space. I could easily store tens of thousands of hashes with the first method with no issues at all. But I like being efficient. I certainly wouldn't want a 5MB file on my computer when I could have the same data in 1.8MB (same compression ratio as above). That's why I save all my PNGs as indexed-palette when possible. Is this a good mentality to have? Or am I just being pedantic? I guess this question could be summarised as: Should I compress, or just not care due to having more resources than I'll ever need? A: Pedantic is good when coming to code. Compress when you can, but be sure that when reading your code, it's still readable and understandable that hashes are kept in whatever way. What I mean is, don't sacrifice your code readability and maintainability for efficiency.
doc_23526831
After packaging the NuGet package and referencing it, the bindings do not seem to be triggering at all from the package. When hovering over the [Binding] keyword, there's no referenced namespace and the text is in white. Is it possible to have BindingAttribute recognized in a NuGet package at all? A: Given you tagged specflow, I assume this question is really "How can I make Specflow use bindings from external assemblies". A quick google search of that question finds this page on the Specflow wiki. The important part from the page: In order to use bindings from an external binding assembly, you have to list it (with the assembly name) in the app.config of the SpecFlow project. The SpecFlow project is always included implicitly. See more details on the configuration in the <stepAssemblies> section of the configuration guide. <specFlow> <stepAssemblies> <stepAssembly assembly="MySharedBindings" /> </stepAssemblies> </specFlow> Otherwise, NuGet doesn't do anything special, it's just a delivery mechanism. By the time the compiler runs, it doesn't know whether each assembly was from a project or package reference. At runtime it's irrelevant. It's common for libraries like MVC or Specflow to only discover classes from the calling assembly, not all assemblies, so you usually have to read the docs of the framework you're using to find out how to register additional assemblies. There is no single or common way, each library or framework has its own technique.
doc_23526832
It's a nightmare to find a kind of HTML-Formatting extension for a VB.NET programmer, all the extensions that I've seen only works for C# like Code4blog extension. A: Use the Copy HTML Markup command from the Edit menu
doc_23526833
I want my web site to validate the address, giving this for an invalid one: "email doesn't exist". How can I do this? My on-line searches have turned up nothing.
doc_23526834
from django.contrib import admin from django.contrib.auth.models import User admin.site.unregister(User) class CustomUserAdmin(admin.ModelAdmin): filter_horizontal = ('groups',) list_display = ('username', 'email', 'last_login') admin.site.register(User, CustomUserAdmin) however after doing this and testing on the admin site the changes aren't reflected. If I remove the last line: admin.site.register(User, CustomUserAdmin) it throws an error saying that User isn't registered so i think it's recognizing the new admin just not taking any effect. A: Not sure if that's a case, but maybe you should inherit from from django.contrib.auth.admin import UserAdmin and not from the ModelAdmin. A: It may be simpler to just override the built-in UserAdmin, changing what you need: from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin admin.site.unregister(User) UserAdmin.filter_horizontal = ('groups',) UserAdmin.list_display = ('username', 'email', 'last_login') admin.site.register(User, UserAdmin)
doc_23526835
I'm using the following code to authenticate it originally. var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(CancellationToken.None); if (result.Credential != null) { var service = new YouTubeService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "YouTube Upload Tool" }); } And this is my AppFlowMetadata class. public class AppFlowMetadata : FlowMetadata { private static readonly IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = "ID", ClientSecret = "SECRET", }, Scopes = new[] { YouTubeService.Scope.YoutubeUpload }, DataStore = new EFDataStore(-1) // A data store I implemented using Entity Framework 6. }); public override string GetUserId(Controller controller) { return "test"; } public override IAuthorizationCodeFlow Flow { get { return flow; } } } If anyone can suggest anything, I would greatly appreciate it. Thank you. A: While this is not an answer, this is how I got around it. I had to create the GET request for authorisation (redirect your user to the url you get back and set your Controller Action to receive the callback specified in your Google Developer Console) and the PUT request for the Token (which I then stored using EF6) manually. I used System.Net.Http.HttpClient to make these requests, which was quite straight forward. See this link for all the details I needed to get this working. It was the only way I could set the access_type to "offline". If the .NET API does this, I'm still curious to find out how. With the token data stored, I now use the API to validate and refresh the token when I need to. I actually did this in a server side console application rather than a MVC app (hence the EF token persistence). UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "ID", ClientSecret = "Secret" }, new[] { YouTubeService.Scope.YoutubeUpload }, "12345", CancellationToken.None, new EFDataStore(-1) // My own implementation of IDataStore ); // This bit checks if the token is out of date, // and refreshes the access token using the refresh token. if(credential.Token.IsExpired(SystemClock.Default)) { if (!await credential.RefreshTokenAsync(CancellationToken.None)) { Console.WriteLine("No valid refresh token."); } } var service = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MY App" }); I hope this helps others.
doc_23526836
In the samples I have seen for Prism the Shell window has no explicit depencies so when it is resolved in the CreateShell of the bootstrapper it all stops there. Because of this modules must be explicitly resolved in the InitializeModules method. Likewise, inserting views into the shell is usually done by resolving them in the module Initialize method and explicitly setting them to a given region, thus using the DI container more as a service locator. Does anybody know how to link things together to enable a single resolve in Prism? A: There is an application which has two modules Module1 and Module2. You are saying the following is public ShellView(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator, IModule1 mod1, IModuel2 mod2) { } better than this public ShellView(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator) { } public class IModule1 : IModule { public void Initialize() { var container = ServiceLocator.Current.GetInstance<IUnityContainer>(); var regionManager = ServiceLocator.Current.GetInstance<IRegionManager>(); regionManager.RegisterViewWithRegion("Region1", typeof(Module1View)); } } public class IModule2 : IModule { public void Initialize() { var container = ServiceLocator.Current.GetInstance<IUnityContainer>(); var regionManager = ServiceLocator.Current.GetInstance<IRegionManager>(); regionManager.RegisterViewWithRegion("Region2", typeof(Module2View)); } } Which way one could do the project depends on many factors. For example I can selct the second approach citing Modularity The second approach is more loose coupled than the first. The first approach forces the app to declare the modules it is going to use. I can decide my app will only define regions and I will create modules later on and inject the views to the respective regions. I am not saying this is absolutely the case as you can very well select the first approach saying as the modules itself won't have any reference about where it is going to be used that approach is more modular. All I am saying is there are options about how to go about a problem and limiting the options is generally not a good idea.
doc_23526837
So I want to schedule a job / task on appengine to run at the events date/time to send a push notification to all subscribers. Example: User A creates an event that will start on Saturday next week on 8 pm. User B and User B subscribe for this event. On Saturday 8 pm a job/task should start to send the push notifications to User B and User C to inform that the event has started. My question is: How do I implement something like this in an efficient way on appengine? I want to say, start a Task for the Event on Saturday at 8 pm. There are Cronjobs and TaskQueues. Cronjobs can not be created programmatically. TaskQueue needs to be pulled and can not be scheduled to pull at a given date / time, right? So the only solutions I see is to create a cronjob that will run every minute to check if there is a Event that starts right now. An event can be created at any time and any day in the week. However the most events are created for the weekend and There are days when no event has been created for. So running a cronjob periodically ever minute is very inefficient. Im looking for a smarter solution, any ideas? A: Indeed, based on your description, the solution is to create a cron job that checks for new events that start right now. However, you should be careful not to exceed the 60 second window you have for each cron job. If you have a lot of events, you probably should move the actual processing from the cron job to background tasks using Push Task Queues. You may take a look to this post for a combination of cron jobs and Task Queues.
doc_23526838
A: OpenOffice's Impress has a Powerpoint import, and Flash export function. I have no idea how it will work for your case, but give it a shot before you start exporting manually. A: I'm using FlashPoint PowerPoint to flash converter, it supports PowerPoint 2003 and 2007, the navigation bar can be hided based on your needs. A: You can use openOffice or powerpoint 2007 (which has in-built xps support) for exporting your presentations into pdf's and then use pdf2swf for converting pdf into swfs. A: There are 6 ways to convert PowerPoint to flash, maybe it helps. A: There are quite a number of converters on the open market. I use Articulate Presenter, which is quite good.
doc_23526839
Error: Cannot find module 'unicode-match-property-value-ecmascript' I have tried installing the dependency using npm install unicode-match-property-value-ecmascript But I get this error on vscode powershell npm ERR! code UNKNOWN npm ERR! syscall rename Any help will be appreciated
doc_23526840
Suppose I have two function one call myfunc, one call do.something. I want to use do.something inside myfunc. myfunc <- function(parA,arglist=list(parB=parA)){ print("parA in myfunc") print(parA) print("....") print("....") do.call("do.something", args=arglist) } do.something <- function(parB){ print("parB in do.something") print(parB) } Now execute it. a.data=matrix(1:9,ncol=3) myfunc(parA=a.data,arglist=list(parB=parA)) [1] "parA in myfunc" [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 [1] "...." [1] "...." Error in do.call("do.something", args = arglist) : object 'parA' not found Inside myfunc, I want to pass parA to parB, but it says parA not found, how to solve it?
doc_23526841
ImportError: could not import module "PySide.QtXml" When I try to convert the app shipped with cx_Freeze\Samples\PyQt4, it runs with no problems. In this sample application there is just a simple QDialog called, but in my application I used QtDesigner for GUI design and I load it with PySide UiLoader directly in my py.file: class MainWindow(QtGui.QMainWindow): def __init__(self,parent=None): QMainWindow.__init__(self) loader = QUiLoader() self.ui = loader.load('xxxx.ui',self) QMetaObject.connectSlotsByName(self) setup.py from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. buildOptions = dict(packages = [], excludes = []) import sys from cx_Freeze import setup, Executable from PySide import QtXml base = 'Win32GUI' if sys.platform=='win32' else None options = { 'build_exe': { 'includes': 'atexit' } } build_exe_options = { 'includes': ['atexit'], } executables = [ Executable('xxx.py', base=base) ] setup(name='xxx', version = '0.10', description = 'First try', options = dict(build_exe = buildOptions), executables = executables) In my opinion there's some problem using UiLoader when converting with cx_freeze but I have no clue how to overcome this issue. A: This seems to be an old question. Still I am answering as it would help someone who is looking for a solution. The solution is so simple that you just need to add "PySide.QtXml" to the includes list. After this your setup.py will look like this build_exe_options = { 'includes': ['atexit'], 'packages': ['PySide.QtXml'], }
doc_23526842
And I want to plot a base map: The question is I can do the two images separately. But when I combine them together, both of them are missing: Can anyone help me find a solution? Thanks. Sorry for not attaching the code. Here it is. #data is a 3d matrix. S is a shapefile. [X,Y,Z]=meshgrid(xgr,ygr,zgr); S = shaperead(filename); hold on; pcolor3(X,Y,Z,data); # show the 3d matrix mapshow(S,'FaceColor',[0.5 0.5 0.5]); # show the base map hold off; I'm not sure if the problem is in function mapshow. When I use mapshow in a 3d scatterplot, it is good. However, this time, it's bad.
doc_23526843
<field source="condition" target="transaction.transactionType"> <ifConditions> <ifCondition operand="isShortSell" operator="eq" expectedValue="true"> <!-- This is available after tranformation> --> <ifCondition operand="quanity" operator="gt" expectedValue="0" /> <!-- This is NOT available after tranformation> --> open </ifCondition> </ifCondition> <ifCondition operand="isShortSell" operator="eq" expectedValue="true"> <!-- This is available after tranformation> --> <ifCondition operand="quanity" operator="lt" expectedValue="0" /> <!-- This is NOT available after tranformation> --> close </ifCondition> </ifCondition> </ifConditions> </field> Below is my current mapping. The current issue i am facing is I am not able to get any of the nested IfCondition objects. How do i transform nested objects, there can be N level of nesting. Am i missing any annotation ? public class Field implements Serializable { private String source; @JsonProperty("source-type") private String sourceType; private String target; @JsonProperty("target-type") private String targetType; @JsonProperty("allow-null") private boolean allowNull; @JsonProperty("default-value") private String defaultValue; @JsonProperty("external-mapping") private String externalMapping; private String pattern; private List<IfCondition> ifConditions; } @XmlRootElement public class IfCondition implements Serializable { private String expectedValue; @XmlElement private String value; private String operand; private String operator; private List<IfCondition> ifCondition; } Am i missing any annotation?
doc_23526844
my code to open webpage and insert user name and password is as below Sub Button173_Click() ' open IE, navigate to the desired page and loop until fully loaded Set ie = CreateObject("InternetExplorer.Application") my_url = "https://www.checkname.com/frontend/login" With ie .Visible = True .Navigate my_url .Top = 50 .Left = 530 .Height = 400 .Width = 400 Do Until Not ie.Busy And ie.readyState = 4 DoEvents Loop End With 'Input the userid and password ie.Document.getElementById("signOnName").Value = "username" ie.Document.getElementById("password").Value = "password" 'Click the "Search" button ie.Document.getElementById("sign-in").Click Do Until Not ie.Busy And ie.readyState = 4 DoEvents Loop End Sub my question is divided into two part : * *how to click on button in a web page ? source code of submit button is <button class="button" type="submit"><span class="bg-left"><span class="bg-right">Login</span></span></button> Login <span class="bg-right">Login</span> *how to past a name in a cell A2 for example into text box in the opened web page and press search then get the link of search result and past it into cell B2? appreciate your support and thanks in advance and would be great to provide sample code .
doc_23526845
import SwiftUI import MapKit struct Response: Codable, Hashable { var District: String var BusinessName: String var LocationAddress: String var LocationCity: String func hash(into hasher: inout Hasher) { hasher.combine(BusinessName) } } struct ContentView: View { @ObservedObject var lm = LocationManager() @State var response = [Response]() @State var search: String = "" @State private var showCancelButton: Bool = false @State private var searchPerfromed: Bool = false @State var location2: CLLocationCoordinate2D? @State var distance: Double = 0 @State var dist: [String: Double] = Dictionary() var body: some View { VStack { HStack { HStack { Image(systemName: "magnifyingglass") TextField("Search", text: $search, onEditingChanged: { isEditing in self.showCancelButton = true }, onCommit: { self.searchPerfromed = true getData() // Function to get JSON data executed after search execution }).foregroundColor(.primary) Button(action: { self.search = "" self.searchPerfromed = false }) { Image(systemName: "xmark.circle.fill").opacity(search == "" ? 0 : 1) } } .padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6)) .foregroundColor(.secondary) .background(Color(.secondarySystemBackground)) .cornerRadius(10.0) if showCancelButton { Button("Cancel") { UIApplication.shared.endEditing(true) self.search = "" self.showCancelButton = false self.searchPerfromed = false } } } .padding(EdgeInsets(top: 10, leading: 0, bottom: 1, trailing: 0)) .padding(.horizontal) Spacer() if searchPerfromed == true { List { ForEach(response.sorted {$0.LocationAddress > $1.LocationAddress}, id: \.self) { item in VStack(alignment: .leading) { HStack(alignment: .center) { Text("\(item.BusinessName)").font(.subheadline) Spacer() if dist[item.LocationAddress] == 0.0 { Text("Unknown").font(.caption).foregroundColor(.gray) } else { Text("\(dist[item.LocationAddress] ?? 0, specifier: "%.0f") mi") .font(.caption).foregroundColor(.gray) } } Text("\(item.LocationAddress), \(item.LocationCity)").font(.subheadline) } } } } } } func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) { let geocoder = CLGeocoder() geocoder.geocodeAddressString(address) { (placemarks, error) in guard let placemarks = placemarks, let location = placemarks.first?.location?.coordinate else { completion(nil) return } completion(location) } } func getDistance() { let loc1 = CLLocation(latitude: lm.location1!.latitude, longitude: lm.location1!.longitude) let loc2 = CLLocation(latitude: location2?.latitude ?? lm.location1!.latitude, longitude: location2?.longitude ?? lm.location1!.longitude) let dist = loc1.distance(from: loc2) distance = dist * 0.00062 // convert from meters to miles } func getData() { let baseURL = "https://???" let combinedURL = baseURL + search let encodedURL = combinedURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let url = URL(string: encodedURL)! URLSession.shared.dataTask(with: url) { (data, response, error) in do { if let responseData = data { let decodedData = try JSONDecoder().decode([Response].self, from: responseData) DispatchQueue.main.async { self.response = decodedData print(decodedData) for item in self.response { let address = item.LocationAddress getLocation(from: address) { coordinates in self.location2 = coordinates getDistance() dist[address] = distance let d = String(format: "%.1f", distance) print(item.District) item[District] = d //Error: Cannot find 'District' in scope } } } } else { print("No data retrieved") } } catch { print("Error: \(error)") } }.resume() } } Just above the issue I assigned the distance value to a new Dictionary and match the values based on address, but this has limitations with other changes I need to make to get to the end state with the app. I have tried lots of different ways to assign the distance to an existing key:value pair in Response or create a new key value pair in Response. Some examples below: item.District = d //Error: Cannot assign to property: 'item' is a 'let' constant item[Distance] = d //Error: Cannot find 'Distance' in scope item["Distance"] = d //Error: Value of type 'Response' has no subscripts How do I create a new key:value pair in Response, or assign the value of d to the District key? Thanks so much in advance for any help you can provide. A: First thing, your instance variables on your Response struct are a little confusing because they don't follow the convention of having variables in all-lowercase, and types capitalized. Second, for your first error in your list of 3, item is a let constant because it is inside a for loop. You can get around this by declaring the loop this way: for var item in self.response { // I can modify item in this loop because it is declared a var } The other two errors are pretty self-explanatory, I think. Third, it sounds like you want to alter your Response object programmatically after receiving it, which is also a bit of an anti-pattern. If you want to modify an object you have downloaded from a server, that's understandable, but it is confusing for someone reading your code to alter an object called "Response." (once you modify it, it no longer represents the server response for which it is named) At a minimum, you could change District to be a computed property of Response. All that said, if you instantiate your loop using the var keyword, you should be able to do: item.District = d
doc_23526846
I'm trying to understand the various tags I'm seeing for the service I"m trying to access specifically the prefix for say envelope and body tags I see <soapenv:Envelope> <soapenv:Body> <s:Envelope> <s:Body> <soap:Envelope> <soap:Body> <soap-env:Envelope> <soap-env:Body> From the service I'm trying to access (Marketing Cloud) the documentation references various tags <soap-ENV:Body>, <s:Envelope>, etc. After trying to get successful response using "Retrieve" Soapaction finally worked by using "<s:Envelope>", "<s:Body>, etc. Is the difference between the tags version 1.2 and another version? I think if I better understand the tags should help understand how to properly submit to the Marketing Cloud service using tools such as Postman. Here are some examples and just not sure how to get these various ones working in Postman Example 1 <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <CreateRequest xmlns="http://exacttarget.com/wsdl/partnerAPI"> <Options> <SaveOptions> <SaveOption> <PropertyName>*</PropertyName> <SaveAction>UpdateAdd</SaveAction> </SaveOption> </SaveOptions> </Options> <Objects xsi:type="Subscriber"> <ObjectID xsi:nil="true"> </ObjectID> <EmailAddress>help@example.com</EmailAddress> <Lists> <ID>123</ID> <ObjectID xsi:nil="true"> </ObjectID> </Lists> </Objects> </CreateRequest> </s:Body> Example 2 <SOAP-ENV:Body> <ns1:UpdateRequest> <ns1:Options/> <ns1:Objects xsi:type="ns1:Subscriber"> <ns1:Attributes> <ns1:Name>First Name</ns1:Name> <ns1:Value>Updated</ns1:Value> </ns1:Attributes> <ns1:Attributes> <ns1:Name>Last Name</ns1:Name> <ns1:Value>ViaAPI</ns1:Value> </ns1:Attributes> <ns1:SubscriberKey>012345</ns1:SubscriberKey> <ns1:Lists> <ns1:ID>12345</ns1:ID> </ns1:Lists> <ns1:Lists> <ns1:ID>12346</ns1:ID> </ns1:Lists> </ns1:Objects> </ns1:UpdateRequest> </SOAP-ENV:Body>
doc_23526847
The game I'm making is called Othello. import pygame, sys import math pygame.init() ROW_COUNT = 8 COLUMN_COUNT = 8 PLAYER_COUNT = 2 RED = (255, 0, 0) BEIGE = (255, 200, 0) BLACK = (0, 0, 0) WHITE = (255, 255, 255) SQUARESIZE = 100 width = COLUMN_COUNT * SQUARESIZE height = ROW_COUNT * SQUARESIZE size = (width, height) screen = pygame.display.set_mode(size) screen.fill(RED) # Vertical one_x_1 = 100 one_y_1 = 0 one_end_x = 100 one_end_y = 800 # Horizontal two_x_1 = 0 two_y_1 = 100 two_end_x = 800 two_end_y = 100 RADIUS = int(SQUARESIZE/2 - 5) def draw_board(board): global one_x_1, one_y_1, one_end_x, one_end_y, two_x_1, two_y_1, two_end_x, two_end_y for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): pygame.draw.line(screen, BLACK, (one_x_1, one_y_1), (one_end_x, one_end_y), 3) one_x_1 += 100 one_end_x += 100 pygame.draw.line(screen, BLACK, (two_x_1, two_y_1), (two_end_x, two_end_y), 3) two_y_1 += 100 two_end_y += 100 for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): if board[r][c] == 1: pygame.draw.circle(screen, WHITE, (int(c*SQUARESIZE+SQUARESIZE/2), height - int(r*SQUARESIZE + SQUARESIZE/2)), RADIUS) elif board[r][c] == 2: pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), height - int(r*SQUARESIZE + SQUARESIZE/2)), RADIUS) pygame.display.update() class Player(object): def __init__(self, number): self.remaining_pieces = 32 self.number = number board = np.zeros((ROW_COUNT, COLUMN_COUNT), dtype=np.uint8) board[3][3] = 1 board[4][4] = 1 board[3][4] = 2 board[4][3] = 2 print(board) draw_board(board) pygame.display.update() players = [Player(i) for i in range(1, PLAYER_COUNT + 1)] print(len(players)) game_over = False while not game_over: # Event loop for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() for p in players: if event.type == pygame.MOUSEBUTTONDOWN: posx = event.pos[0] posy = event.pos[1] column = int(math.floor(posx/SQUARESIZE)) row = int(math.floor(posy/SQUARESIZE)) if board[row][column] == 0: board[row][column] = p.number p.remaining_pieces = p.remaining_pieces - 1 # The eight directions in which we will go directions = [(-1, -1), (-1, 0), (-1, 1), (1, 1), (1, 0), (1, -1), (0, 1), (0, -1)] for d in directions: x = row y = column while True: x = x + d[0] # Assign x to the first value in the tuple y = y + d[1] # Assign y to the second value in the tuple # check if we are still on the board if (x in range(8)) and (y in range(8)): print(f'checking y = {x + 1}, x = {y + 1}') # if the file is empty there are no pieces to capture if board[x][y] == 0: break """ If we find a number around our move we run the same procedure for it and change it if we have to """ if p.number == board[x][y]: # Here p.number is the players move we find it on the board print(f'found {p.number}: y = {x + 1}, x = {y + 1}') i = row j = column while i != x or j != y: i = i + d[0] j = j + d[1] print(f'changed : y = {i + 1}, x = {j + 1} to {p.number}') board[i][j] = p.number else: # We are outside the board break draw_board(board) print(board)``` A: I will go step by step through your program and improve it. First of all creating arrays like this: player1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] player2 = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] Is always a bad practice. Since you already use numpy in your project it's easy to create them like this: player1 = np.ones(32, dtype=np.uint8) player2 = np.full(32, 2, dtype=np.uint8) However you don't really need those arrays anyway. You can just have an integer which keeps track of the remaining pieces. reamining_pieces = 32 To make the whole think easier I created a Player class which contains a Player number and the remaining Pieces. class Player(object): def __init__(self, number): self.remaining_pieces = 32 self.number = number Now after this you have a lot of functions which aren't really necessary. They are so simple that there is no advantage of writing a function for them. So for example instead of writing def create_board(): board = np.zeros((ROW_COUNT, COLUMN_COUNT)) return board board = create_board() It's a lot simpler and easier to read if you just write board = np.zeros((ROW_COUNT, COLUMN_COUNT)) Same goes for def drop_piece(board, row, col, piece) and def is_valid_location(board, row, col) which both just add unnecessary complexity to it. Step by step explanation First, we start with a tuple of all directions: directions = [(-1, -1), (-1, 0), (-1, 1), (1, 1), (1, 0), (1, -1), (0, 1), (0, -1)] And we now want to go in all directions and every time we start at row, column which is where the newly placed piece is located. for d in directions: x = row y = column And since we don't know how far we have to go we use a while loop and take the first step in the direction. Because We don't want to go outside of the board we immediately check if we are still on the board. If we are, we can continue. while True: x = x + d[0] y = y + d[1] # check if we are still on the board if (x in range(8)) and (y in range(8)): For the following steps let's use this as an example: [[0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0] [0 0 0 1 2 0 0 0] [0 0 * 2 1 0 0 0] [0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0]] The star is where has just been placed a one. If we go one step to the left, we will encounter a 0 and know that we don't have to go any further. That's what if board[x][y] == 0: break Does. If we now go to the right. We will first encounter a two and it just get's ignored and we go one step further to the right. Here we finally find a one. So we know that between row, column and x, y every number can be converted to a one. To do that we start at row, column and move once again until we reach x, y. On the way we convert every number to a one: if p.number == board[x][y]: print(f'found {p.number}: x = {x + 1}, y = {y + 1}') i = row j = column while i != x or j != y: i = i + d[0] j = j + d[1] print(f'changed : x = {i + 1}, y = {j + 1} to {p.number}') board[i][j] = p.number Whole Code import pygame, sys import math import numpy as np pygame.init() ROW_COUNT = 8 COLUMN_COUNT = 8 PLAYER_COUNT = 2 RED = (255, 0, 0) BEIGE = (255, 200, 0) BLACK = (0, 0, 0) WHITE = (255, 255, 255) SQUARESIZE = 100 width = COLUMN_COUNT * SQUARESIZE height = ROW_COUNT * SQUARESIZE size = (width, height) screen = pygame.display.set_mode(size) screen.fill(RED) # Vertical one_x_1 = 100 one_y_1 = 0 one_end_x = 100 one_end_y = 800 # Horizontal two_x_1 = 0 two_y_1 = 100 two_end_x = 800 two_end_y = 100 RADIUS = int(SQUARESIZE / 2 - 5) def draw_board(board): global one_x_1, one_y_1, one_end_x, one_end_y, two_x_1, two_y_1, two_end_x, two_end_y for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): pygame.draw.line(screen, BLACK, (one_x_1, one_y_1), (one_end_x, one_end_y), 3) one_x_1 += 100 one_end_x += 100 pygame.draw.line(screen, BLACK, (two_x_1, two_y_1), (two_end_x, two_end_y), 3) two_y_1 += 100 two_end_y += 100 for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): if board[r][c] == 1: pygame.draw.circle(screen, WHITE, ( int(c * SQUARESIZE + SQUARESIZE / 2), height - int(r * SQUARESIZE + SQUARESIZE / 2)), RADIUS) elif board[r][c] == 2: pygame.draw.circle(screen, BLACK, ( int(c * SQUARESIZE + SQUARESIZE / 2), height - int(r * SQUARESIZE + SQUARESIZE / 2)), RADIUS) pygame.display.update() class Player(object): def __init__(self, number): self.remaining_pieces = 32 self.number = number board = np.zeros((ROW_COUNT, COLUMN_COUNT), dtype=np.uint8) board[3][3] = 1 board[4][4] = 1 board[3][4] = 2 board[4][3] = 2 print(board) draw_board(board) pygame.display.update() players = [Player(i) for i in range(1, PLAYER_COUNT + 1)] print(len(players)) def next_player(): while True: for player in players: yield player player_generator = next_player() game_over = False while not game_over: # Event loop for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: posx = event.pos[0] posy = event.pos[1] column = int(math.floor(posx / SQUARESIZE)) row = int(math.floor(posy / SQUARESIZE)) p = player_generator.__next__() if board[row][column] == 0: board[row][column] = p.number p.remaining_pieces = p.remaining_pieces - 1 # The eight directions in which we will go directions = [(-1, -1), (-1, 0), (-1, 1), (1, 1), (1, 0), (1, -1), (0, 1), (0, -1)] for d in directions: x = row y = column while True: x = x + d[0] # Assign x to the first value in the tuple y = y + d[1] # Assign y to the second value in the tuple # check if we are still on the board if (x in range(8)) and (y in range(8)): print(f'checking y = {x + 1}, x = {y + 1}') # if the file is empty there are no pieces to capture if board[x][y] == 0: break """ If we find a number around our move we run the same procedure for it and change it if we have to """ if p.number == board[x][y]: # Here p.number is the players move we find it on the board print(f'found {p.number}: y = {x + 1}, x = {y + 1}') i = row j = column while i != x or j != y: i = i + d[0] j = j + d[1] print(f'changed : y = {i + 1}, x = {j + 1} to {p.number}') board[i][j] = p.number else: # We are outside the board break draw_board(board) print(board)
doc_23526848
http://weblink.computersforpeople.info/users/1/properties/518/images/2869 why it doesn't work in Internet Explorer, but ok for other browser. Many thanks A: IE cannot read your imagearray. Your last image in the array has a comma after it, followed by a comment stating to not include a comma after the last element. The IE error indicates your imagearray is empty, I suspect this is the problem.
doc_23526849
Engine: PCRE RegEx1: (?<=<prefix>)(.*)(?=<suffix1>) RegEx2: (?<=<prefix>)(.*)(?=<suffix2>) Result1: <content1> Result2: <content1><suffix1><prefix><content2> The desired result for RegEx2 is just <content2> but it is obviously greedy. How do I make RegEx2 non-greedy and use only the last matching lookbehind? [I hope I have translated this correctly from the NoteTab syntax. I don't do much RegEx coding. The <prefix>, <content> & <suffix> terms are just meant to represent arbitrary strings. Only the "<" in the "?<=" lookbehind command is significant.] I suspect it is something simple but after too many hours of searching I'm giving up on solving it myself. Thanks for the help Art A: I suggest you use: (?<=<prefix>)(((?!<prefix>).)*)(?=<suffix2>) This makes sure that there can be no <prefix> inside the match. The complete match result will be <content2> A: Put something greedy in front of it? (?:.*)(?<=<prefix>)(.*)(?=<suffix2>) Since the greedy (?:.*) will gobble as much as it can, only the minimum will be matched by the rest of the pattern - effectively making the rest non-greedy. The non-greedy .*? might also work: (?<=<prefix>)(.*?)(?=<suffix2>) A: I just had the same problem. But in my case it was (?<=<prefix>)(?:.(?!<prefix>))*(?=<suffix>) That did what I wanted. This expression will match anything that is a concatenation of characters between <prefix> and <suffix> and doesn't contain the substring <prefix>. (I think so. I'm not very good at regexp.)
doc_23526850
Such that in case connection is lost to a server due to loss of internet connection, there is a possibility to communicate between all devices with software containing peer to peer connections made through WebRTC without being connected to cell towers or the internet. A: There could be a couple of different ideas mixed into your question, so it may be worth being quite precise in the answer. WebRTC is IP and HTTP based, as mentioned in the comments, so it does need IP connectivity, but that connectivity could be a private network and not necessarily the internet, if both devices were connected to the same private network, or to two interconnected private networks. However, you also say that cell towers are down - in this case there would be no connectivity to the cellular network, so the devices would only be able to communicate if they both had WiFi capabilities and were connected to the same WiFi networks, or to separate WiFi networks that had some sort of connection between them (I'm ignoring wired connections to the devices as I doubt this is what you are thinking of). If you meant, could phones connect in a peer to peer manner if the network went down so they could work together to make and route calls, this is something which has been discussed and looked at quite extensively and certainly chat apps existed and exist which can do this, possibly the best known being the now discontinued FireChat (https://en.wikipedia.org/wiki/FireChat). Its a constantly evolving field so any links will age quickly, but if you search for 'Mobile Mesh Networking' you will usually find the right material. And, in answer to your original question - WebRTC itself does not enable peer to peer connectivity.
doc_23526851
<int-kafka:message-driven-channel-adapter id="kafkaListener" listener-container="container1" auto-startup="false" phase="100" send-timeout="5000" channel="nullChannel" message-converter="messageConverter" error-channel="errorChannel" /> However, when i was testing it with downstream application where i consume from kafka and publish it to downstream. If downstream is down, the messages were still getting consumed and was not replayed. Or lets say after consuming from kafka topic , in case i find some exception in service activator, i want to throw some exception as well which should rollback the transaction so that kafka messages can be replayed. In brief, if the consuming application is having some issue , then i want to roll back the transaction so that messages are not automatically acknowledged and are replayed back again and again unless it is succesfuly processed. A: That's not how Apache Kafka works. There is the TX semantics similar to JMS. The offset in Kafka topic has nothing with rallback or redelivery. I suggest you to study Apache Kafka closer from their official resource. Spring Kafka brings nothing over the regular Apache Kafka protocol, however you can consider to use retry capabilities in the Spring Kafka to redeliver the same record locally : http://docs.spring.io/spring-kafka/docs/1.2.2.RELEASE/reference/html/_reference.html#_retrying_deliveries And yes, the ack mode must be MANUAL, do not commit offset into the Kafka automatically after consuming.
doc_23526852
Thank you for you help, I have already dedicated a great amount of time for the code and I am still lost at the end, where I want to verified by recursion if the sum of V[n] will be or not too high, I don't think the end of my code is well thinked. V=[1,2,3,4,5,6,7,8,9,10] C = 9 def Vmax(V, n, C, T): if n ==-1: return(T) else: if C < V[n]: Vmax(V, n-1, C, T) else: if V[n]== C: T.append(V[n]) Vmax(V, n-1, C, T) # Troubles starts here elif V[n] < C: for k in range(1,n): if k - n == -2: T.append(V[n]) if V[n] + Vmax(V, n-k, C, T) < C: T.append(V[n] + Vmax(V, n-k, C, T)) else: Vmax(V, n-1, C, T) print(Vmax(V, len(V)-1, C, T))```
doc_23526853
I want to update the "remaining" labels when a row is either inserted or deleted. The problem comes when I call my "setLabels" method in controller didChangeObject: delete and insertRowAtIndexPaths. With this (https://www.dropbox.com/s/fcj8h3a03pfud6x/Screenshot%202015-02-04%2019.11.46.png?dl=0 ) implementation the labels only update when the next cycle comes. (If i add one, nothing will happen until I add another or delete one. I'm left with the label values that correspond to the tableView before the most recent change. Always one step behind) I added an NSLog to verify the method is being called (it is) so I have no idea why my labels won't update till controllerWillChangeContent is called for a second time. PS: my set labels method is simple. It uses my "getSum" method which gets the sum of an entities attribute and sets the label
doc_23526854
char string[30]; int hmanyt; struct Tree * left; struct Tree * right; }; typedef struct Tree * drzewo; void printftree(drzewo* korzen) { if((*korzen)->left != NULL) printftree(&((*korzen)->left)); printf("%s(%d)\n",(*korzen)->string,(*korzen)->hmanyt); if(strcmp((*korzen)->string,"boril\0")==0) (((*korzen)->right)->left)->left=NULL; if((*korzen)->right != NULL) printftree(&((*korzen)->right)); return ; } void erease(drzewo* korzen) { if((*korzen)->left==NULL && (*korzen)->right==NULL) { *korzen=NULL; free (*korzen); return ; } else { if((*korzen)->left !=NULL) { erease(&((*korzen)->left)); (*korzen)->left=NULL; free((*korzen)->left); } if((*korzen)->right !=NULL) { erease(&((*korzen)->right)); (*korzen)->right=NULL; free((*korzen)->right); } } *korzen=NULL; free(*korzen); return ; } void add(drzewo* korzen,char word[]) { while(*korzen!=NULL) { if(strcmp((*korzen)->string,word)==0) { ((*korzen)->hmanyt)++; return; } else if(strcmp((*korzen)->string,word)<0) { korzen=&((*korzen)->right); } else if(strcmp((*korzen)->string,word)>0) { korzen=&((*korzen)->left); } } *korzen=(drzewo) malloc(sizeof(drzewo)); strcpy(((*korzen)->string),word); printf("%p",(*korzen)->left); printf("%p\n",(*korzen)->right); (*korzen)->hmanyt=1; return; } int main() { drzewo korzen =NULL; char *words[10]={"alfabet","borixon","aaaaaa","zombie","bobas","kamil","agnieszka","kokos","zamach"}; for(int i=0;i<9;i++) add(&korzen,words[i]); printf("test1\n"); printftree(&korzen); printf("test"); erease(&korzen); return 0; } So this is my implementation of binary tree. Which loads 10 words to the tree . Sadly during 'printing' this tree I came across a problem which is core dumped. I don't know why but one of the structurs "has" (*korzen)->left that isn't NULL, my funcion wants to acess it,and the core dumped appears. After adding two lines if(strcmp((*korzen)->string,"boril\0")==0) (((*korzen)->right)->left)->left=NULL; it works fine, but I don't know why i have this issue. Another issue is that despite having such a line as: (*korzen)->hmanyt=1; Afterall it doesn't have this value ... (only first word has hmanyt==1) . Help would be really appreciated. A: It is a bad idea to assign NULL to a pointer which you want to free. Change place of *korzen=NULL; and free(*korzen); in your function erease: Adapt your function erease like this: void erease(drzewo* korzen) { if ( *korzen == NULL ) return; if( (*korzen)->left !=NULL ) { erease(&((*korzen)->left)); // (*korzen)->left is freed in erease } if( (*korzen)->right !=NULL ) { erease(&((*korzen)->right)); // (*korzen)->right is freed in erease } free(*korzen); *korzen=NULL; return; } If you insert a new node in your tree you have to initialize its childs (*korzen)->left and (*korzen)->right with NULL. Further the type of drzewo is struct Tree*, so sizeof(drzewo) gives the size of a pointer not the size of struct Tree. void add(drzewo* korzen,char word[]) { while( *korzen != NULL ) { int cmp = strcmp( ( *korzen )->string, word ); if ( cmp == 0 ) { ((*korzen)->hmanyt)++; return; } else if( cmp<0 ) { korzen=&((*korzen)->right); } else if (cmp>0 ) { korzen=&((*korzen)->left); } } // allocate new node and initiialize *korzen=malloc(sizeof(struct Tree)); // allocat sizeof struct Tree ( not sizeof pointer to Tree) ( *korzen )->left = NULL; // <- left child is null ( *korzen )->right = NULL; // <- right child is null strcpy(((*korzen)->string),word); (*korzen)->hmanyt=1; return; } Finally your function printftree: void printftree(drzewo* korzen) { if ( *korzen == NULL ) return; if( (*korzen)->left != NULL) printftree(&((*korzen)->left)); printf("%s(%d)\n",(*korzen)->string,(*korzen)->hmanyt); if((*korzen)->right != NULL) printftree(&((*korzen)->right)); return ; }
doc_23526855
Thanks in Advance.
doc_23526856
Thank you! BundleConfig.cs var nullBuilder = new NullBuilder(); var styleTransformer = new StyleTransformer(); var scriptTransformer = new ScriptTransformer(); var nullOrderer = new NullOrderer(); var defaultScssBundle = new CustomStyleBundle("~/bundles/styles/default"); defaultScssBundle.Include( "~/Content/Default.scss" ); defaultScssBundle.Builder = nullBuilder; defaultScssBundle.Transforms.Add(styleTransformer); defaultScssBundle.Transforms.Add(new CssMinify()); defaultScssBundle.Orderer = nullOrderer; bundles.Add(defaultScssBundle); Default.scss @import "bootstrap/bootstrap.scss"; /* common styles */ .green { color: green; } .full-width { width: 100%; } Error During translation of SCSS code, readed from the file '/TestProject/Content/bootstrap/_alert.scss', to CSS code syntax error has occurred. See more details: Error: Undefined variable: "$alert-padding-y". on line 7:12 of Content/bootstrap/_alert.scss >> padding: $alert-padding-y $alert-padding-x; -----------^ Error code: 1 Description: Undefined variable: "$alert-padding-y". File: /TestProject/Content/bootstrap/_alert.scss Line number: 7 Column number: 12 Source fragment: Line 6: position: relative; Line 7: padding: $alert-padding-y $alert-padding-x; -------------------^ Line 8: margin-bottom: $alert-margin-bottom; A: After much trial and error, I found the problem. After looking at the sample in the Github Repo, I pulled the following lines out of BundleConfig.cs and all is working now. defaultScssBundle.Builder = nullBuilder; defaultScssBundle.Transforms.Add(styleTransformer); defaultScssBundle.Transforms.Add(new CssMinify());
doc_23526857
In Java I have written the following regex, and looks like that's what i need: String regex = "([\\w&&\\D]|[\\u0410-\\u044F]|[\\s])+" In GWT this works not as intended: it accepts #$%^... etc signs. I have to write the first group as [a-zA-Z_] to get what I want: letters and _ sign. Moreover, before my modification, there was an old regex, which looked like String regex = "([\\w&&\\D]+|[\\u0410-\\u044F]+|[\\s]+)"; Basing on my Java experience it should accept only words combined from Latin letters and _ sign, or words combined only of Cyrillic letters or words from whitespace. But in fact in GWT it accepts all words, and even &*(... etc signs. So the questions are: 1) Why is [\\w&&\\D] not equivalent to [a-zA-Z_] in GWT? 2) Why does [...]+|[...]+|[...]+ in GWT behave like ([...]|[...]|[...])+ in Java? A: GWT generates JS, so the reason could be the regexp differences between JS and Java.
doc_23526858
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE `USER`='trial_505813'; then KILL 25685; But can I do something like: KILL (SELECT `ID` FROM INFORMATION_SCHEMA.PROCESSLIST WHERE `USER`='trial_505813') to kill all processes from specified user with one query? A: MariaDB has a KILL USER <name> command: https://mariadb.com/kb/en/kill/ MySQL does not implement this feature. You would have to fetch all the process id's for that user and write a loop to kill them one by one. Example in Python: import mysql.connector cnx = mysql.connector.connect(user='root', password='xxxx', database='test') cursor = cnx.cursor() cursor.execute("SELECT id FROM INFORMATION_SCHEMA.PROCESSLIST WHERE USER = %s", ["trial_505813"]) result = cursor.fetchall() for row in result: cursor.execute(f"KILL {row[0]}") I have to comment that killing queries or threads because of a lock wait timeout seems like a harsh solution. It's likely that you could optimize queries so they don't hold locks too long. If the query is already optimized, you could be letting a transaction remain uncommitted too long. A transaction holds locks until the transaction is finished. So you need to finish transactions (COMMIT or ROLLBACK) promptly after the query is done.
doc_23526859
My problem is when tapping on navigation bar, it doesn't update the TabBarView body e.g. RankingTable doesn't update; in the demo code below I have put the same data in the table but the date drop down above the table should be formatted differently since I pass in a different formatter into each datatable when navigation bar is tapped. Namely, in the 2nd screenshot, on Nav1, it still shows the same dropdown date format as in the 1st screenshot which is on Nav0. Screenshot1: Screenshot2: If I put a simple widget such as Text in the TabBarView body, then it updates as expected when tapping on the navigation bar items, not sure whether this implies the problem is my custom RankingTable widget. Also, despite the body doesn't update when tapping on a new item in navigation bar, if I switch tab e.g. from Tab1 to Tab2 and switch it back to Tab1, then the body gets updated correctly, matching with the corresponding navigation bar item. It feels like the body data did get updated when tapping navigation but it just didn't get rendered. import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; void main() => runApp(new Demo()); class Demo extends StatefulWidget { @override _DemoState createState() => _DemoState(); } class _DemoState extends State<Demo> with TickerProviderStateMixin { int _currentIndex = 0; Map<DateTime, List<RankingBase>> _playerDateRanking; TabController controller; List<_NavigationIconView> _navigationIconViews; @override void initState() { super.initState(); controller = TabController(length: 2, vsync: this); _navigationIconViews = <_NavigationIconView>[ _NavigationIconView( icon: Icon(Icons.calendar_view_day), title: 'Nav0', color: Colors.deepOrange, vsync: this, ), _NavigationIconView( icon: Icon(Icons.date_range), title: 'Nav1', color: Colors.deepOrange, vsync: this, ), ]; _playerDateRanking = { DateTime(2018, 9, 10): [ PlayerRanking('Tony', 7, 6, 140, 110, 80), PlayerRanking('John', 7, 2, 120, 130, 56), PlayerRanking('Mike', 8, 5, 120, 130, 70), PlayerRanking('Clar', 6, 2, 100, 134, 63) ], DateTime(2018, 9, 12): [ PlayerRanking('Tony', 7, 6, 140, 110, 80), PlayerRanking('John', 7, 2, 120, 130, 56), PlayerRanking('Mike', 8, 5, 120, 130, 70), PlayerRanking('Clare', 6, 2, 100, 134, 63), PlayerRanking('Jo', 5, 1, 100, 134, 63) ] }; } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( bottom: TabBar( controller: controller, tabs: <Widget>[Text('Tab1'), Text('Tab2')], ), ), body: TabBarView( controller: controller, //TabController(length: 2, vsync: this), children: <Widget>[ buildRankingTable(_currentIndex), Text('TEst'), ], ), bottomNavigationBar: BottomNavigationBar( currentIndex: _currentIndex, items: _navigationIconViews.map((x) => x.item).toList(), onTap: (int index) { setState(() { _currentIndex = index; }); }, ), ), ); } Widget buildRankingTable(int currentIndex) { if (currentIndex == 0) { return RankingTable(_playerDateRanking, dateFormatter: 'yMMMEd'); } else if (currentIndex == 1) { return RankingTable(_playerDateRanking, dateFormatter: 'MMMM'); // different date formatter here! } return Text('TODO...'); } } class _NavigationIconView { _NavigationIconView({ Widget icon, //Widget activeIcon, String title, Color color, TickerProvider vsync, }) : _icon = icon, _color = color, _title = title, item = new BottomNavigationBarItem( icon: icon, // activeIcon: activeIcon, title: new Text(title), backgroundColor: color, ), controller = new AnimationController( duration: kThemeAnimationDuration, vsync: vsync, ) { _animation = new CurvedAnimation( parent: controller, curve: const Interval(0.5, 1.0, curve: Curves.fastOutSlowIn), ); } final Widget _icon; final Color _color; final String _title; final BottomNavigationBarItem item; final AnimationController controller; CurvedAnimation _animation; } class PlayerRanking extends RankingBase { String name; PlayerRanking(this.name, played, won, pointsWon, pointsLost, duration) : super(played, won, pointsWon, pointsLost, duration); } class RankingBase { DateTime date; int won; int played; int duration; int pointsWon; int pointsLost; double get winRatio => won / played; RankingBase( this.played, this.won, this.pointsWon, this.pointsLost, this.duration); static int performanceSort(RankingBase rb1, RankingBase rb2) { if (rb1.winRatio > rb2.winRatio) return -1; if (rb1.winRatio < rb2.winRatio) return 1; if (rb1.played > rb2.played) return -1; if (rb2.played == rb2.played) return rb1.pointsWon.compareTo(rb2.pointsWon); return -1; } } // this puts a scrollable datatable and optionally a header widget into a ListView class RankingTable extends StatefulWidget { final Map<DateTime, List<RankingBase>> rankingMap; final bool hasHeaderWidget; final String dateFormatter; //final bool isPlayer; RankingTable(this.rankingMap, {this.dateFormatter, this.hasHeaderWidget = true}); @override _RankingTableState createState() => _RankingTableState(this.rankingMap, dateFormatter: this.dateFormatter, hasHeaderWidget: this.hasHeaderWidget); } class _RankingTableState extends State<RankingTable> { Map<DateTime, List<RankingBase>> rankingMap; final bool hasHeaderWidget; final String dateFormatter; //final bool isPlayer; _RankingTableState(this.rankingMap, {this.dateFormatter, this.hasHeaderWidget = true}); DateTime _selectedDate; @override initState() { super.initState(); _selectedDate = rankingMap.keys.last; } DataTable buildRankingTable() { rankingMap[_selectedDate].sort(RankingBase.performanceSort); String nameOrPair = rankingMap[_selectedDate].first is PlayerRanking ? 'Name' : 'Pair'; int rank = 1; return DataTable( columns: <DataColumn>[ DataColumn(label: Text('Rank')), DataColumn(label: Text(nameOrPair)), DataColumn(label: Text('Played')), DataColumn(label: Text('Win Ratio')), DataColumn(label: Text('Points Won-Loss')), DataColumn(label: Text('Duration')), ], rows: rankingMap[_selectedDate].map((RankingBase pr) { DataCell titleCell; if (pr is PlayerRanking) titleCell = DataCell(Text('${pr.name}')); else { // var pair = pr as PairRanking; // titleCell = DataCell(Text('${pair.player1Name}\n${pair.player2Name}')); } return DataRow(cells: [ DataCell(Text('${rank++}')), titleCell, DataCell(Text('${pr.played}')), DataCell(Text('${NumberFormat("0.##%").format(pr.won / pr.played)}')), DataCell(Text('${pr.pointsWon} - ${pr.pointsLost}')), DataCell(Text('${pr.duration}')), ]); }).toList(), ); } @override Widget build(BuildContext context) { List<Widget> childrenWidgets = []; if (hasHeaderWidget) { var dateDropdown = DropdownButton<DateTime>( items: rankingMap.keys .map((date) => DropdownMenuItem( child: Text( '${DateFormat(dateFormatter).format(date)}'), //yMMMEd value: date, )) .toList(), value: _selectedDate, onChanged: (value) { setState(() { _selectedDate = value; }); }, ); childrenWidgets.add(dateDropdown); } childrenWidgets.add(SingleChildScrollView( padding: EdgeInsets.all(20.0), scrollDirection: Axis.horizontal, child: buildRankingTable(), )); return ListView( padding: EdgeInsets.all(10.0), children: childrenWidgets, ); } } A: The problem lies in your State. First, there is no need for a constructor in your state. You can access the variables of your widget by calling widget.youFinalField. The problem is: when you return a new RankingTable the underlying state is not recreated but rebuilt (the build and the didUpdateWidget methods are called). Because you passed you variables in the construct (which is only used the very first time) your formatter doesn't update. The solution is pretty simple, instead of using a constructor in your state just access the variables through the widget. Working code state code: // this puts a scrollable datatable and optionally a header widget into a ListView class RankingTable extends StatefulWidget { final Map<DateTime, List<RankingBase>> rankingMap; final bool hasHeaderWidget; final String dateFormatter; //final bool isPlayer; RankingTable(this.rankingMap, {this.dateFormatter, this.hasHeaderWidget = true}); @override _RankingTableState createState() => _RankingTableState(); } class _RankingTableState extends State<RankingTable> { DateTime _selectedDate; @override void initState() { super.initState(); _selectedDate = widget.rankingMap.keys.last; } DataTable buildRankingTable() { widget.rankingMap[_selectedDate].sort(RankingBase.performanceSort); String nameOrPair = widget.rankingMap[_selectedDate].first is PlayerRanking ? 'Name' : 'Pair'; int rank = 1; return DataTable( columns: <DataColumn>[ DataColumn(label: Text('Rank')), DataColumn(label: Text(nameOrPair)), DataColumn(label: Text('Played')), DataColumn(label: Text('Win Ratio')), DataColumn(label: Text('Points Won-Loss')), DataColumn(label: Text('Duration')), ], rows: widget.rankingMap[_selectedDate].map((RankingBase pr) { DataCell titleCell; if (pr is PlayerRanking) titleCell = DataCell(Text('${pr.name}')); else { // var pair = pr as PairRanking; // titleCell = DataCell(Text('${pair.player1Name}\n${pair.player2Name}')); } return DataRow(cells: [ DataCell(Text('${rank++}')), titleCell, DataCell(Text('${pr.played}')), DataCell(Text('')), DataCell(Text('${pr.pointsWon} - ${pr.pointsLost}')), DataCell(Text('${pr.duration}')), ]); }).toList(), ); } @override Widget build(BuildContext context) { List<Widget> childrenWidgets = []; if (widget.hasHeaderWidget) { var dateDropdown = DropdownButton<DateTime>( items: widget.rankingMap.keys .map((date) => DropdownMenuItem( child: Text( '$date ${widget.dateFormatter}'), //yMMMEd value: date, )) .toList(), value: _selectedDate, onChanged: (value) { setState(() { _selectedDate = value; }); }, ); childrenWidgets.add(dateDropdown); } childrenWidgets.add(SingleChildScrollView( padding: EdgeInsets.all(20.0), scrollDirection: Axis.horizontal, child: buildRankingTable(), )); return ListView( padding: EdgeInsets.all(10.0), children: childrenWidgets, ); } } A: The reason why RankingTable doesn't change is because build method in the code uses fields (rankingMap, dateFormatter, etc.) stored in your state. When StatefulWidget is created for the first time, it also instantiates relevant State object which then builds your widget in build method. Every time you call setState method, Flutter recreates Widget from scratch, whereas State object is being persisted. Widgets are temporary objects, used to construct a presentation of the application in its current state. State objects on the other hand are persistent between calls to build(), allowing them to remember information. This means, every time RankingTable widget is created, your build method in _RankingTableState makes use of the same values passed in the constructor/assigned in initState (even though widget object contains updated fields values). On the other hand, when you naviagte back and forth by using the TabBar, state object is recreated with current dateFormatter - that's why the table is updated in this scenario. To make it work as intended, you should remove all final fields from your state object and refer directly to its widget to get all necessary values: class RankingTable extends StatefulWidget { final Map<DateTime, List<RankingBase>> rankingMap; final bool hasHeaderWidget; final String dateFormatter; RankingTable(this.rankingMap, {this.dateFormatter, this.hasHeaderWidget = true}); @override _RankingTableState createState() => _RankingTableState(); } class _RankingTableState extends State<RankingTable> { DateTime _selectedDate; @override initState() { super.initState(); _selectedDate = widget.rankingMap.keys.last; } DataTable buildRankingTable() { widget.rankingMap[_selectedDate].sort(RankingBase.performanceSort); String nameOrPair = widget.rankingMap[_selectedDate].first is PlayerRanking ? 'Name' : 'Pair'; int rank = 1; return DataTable( columns: <DataColumn>[ DataColumn(label: Text('Rank')), DataColumn(label: Text(nameOrPair)), DataColumn(label: Text('Played')), DataColumn(label: Text('Win Ratio')), DataColumn(label: Text('Points Won-Loss')), DataColumn(label: Text('Duration')), ], rows: widget.rankingMap[_selectedDate].map((RankingBase pr) { DataCell titleCell; if (pr is PlayerRanking) titleCell = DataCell(Text('${pr.name}')); else { // var pair = pr as PairRanking; // titleCell = DataCell(Text('${pair.player1Name}\n${pair.player2Name}')); } return DataRow(cells: [ DataCell(Text('${rank++}')), titleCell, DataCell(Text('${pr.played}')), DataCell(Text('${NumberFormat("0.##%").format(pr.won / pr.played)}')), DataCell(Text('${pr.pointsWon} - ${pr.pointsLost}')), DataCell(Text('${pr.duration}')), ]); }).toList(), ); } @override Widget build(BuildContext context) { List<Widget> childrenWidgets = []; if (widget.hasHeaderWidget) { var dateDropdown = DropdownButton<DateTime>( items: widget.rankingMap.keys .map((date) => DropdownMenuItem( child: Text( '${DateFormat(widget.dateFormatter).format(date)}'), //yMMMEd value: date, )) .toList(), value: _selectedDate, onChanged: (value) { setState(() { _selectedDate = value; }); }, ); childrenWidgets.add(dateDropdown); } childrenWidgets.add(SingleChildScrollView( padding: EdgeInsets.all(20.0), scrollDirection: Axis.horizontal, child: buildRankingTable(), )); return ListView( padding: EdgeInsets.all(10.0), children: childrenWidgets, ); } }
doc_23526860
mailer.js import express from 'express'; import expressAsyncHandler from 'express-async-handler'; import nodemailer from 'nodemailer'; import hbs from 'nodemailer-express-handlebars'; import Order from './models/orderModel.js'; const mailerRouter = express.Router(); mailerRouter.post ( '/order', expressAsyncHandler(async (req, res) => { const email = req.body.email const orderId = req.body.orderId const em = req.body.em const sender = req.body.sender const emailBody = await Order.findById(orderId).exec((err, orderData) => { if (orderData) { res.render('orders', {data:orderData}) } }) const sub = `Order: ${orderId}` let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', service: 'gmail', auth: { type: 'OAuth2', user: sender, pass: '', clientId: '', clientSecret: '', refreshToken: '', } }) transporter.use('compile', hbs({ viewEngine: 'express-handlebars', viewPath:'./views/' })) const mailOptions = { from: sender, to: em, subject: sub, text: "Hello world?", // plain text body template: 'orders', } console.log(mailOptions.subject) transporter.sendMail(mailOptions, function (err, info) { if(err) console.log(err) else console.log(info); }); })) export default mailerRouter; server.js import express from 'express'; import cors from 'cors'; import mongoose from 'mongoose'; import dotenv from 'dotenv'; import path from 'path'; import hbs from 'express-handlebars'; import returnRouter from './routers/returnRouter.js'; import mailerRouter from './mailer.js'; dotenv.config(); const app = express(); app.use(cors()); //and thisnp app.use(express.json()); app.use(express.urlencoded({ extended: true })); mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/AM', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); app.use('/api/orders', orderRouter); app.use('/api/mailer', mailerRouter); app.get('/', (req, res) => { res.send('Server is ready'); }); app.engine('hbs', hbs({ defaultLayout: 'template', extname: '.hbs', })); app.set('views', __dirname + '/views'); app.set('view engine', 'hbs'); app.use((err, req, res, next) => { res.status(500).send({ message: err.message }); }); const port = process.env.PORT || 5000; app.listen(port, () => { console.log(`Serve at http://localhost:${port}`); }); orders.hbs (within a views folder) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> </style> </head> <body> {{#each data.orderItems}} <div> <h1>{{name}}</h1> </div> {{/each}} </body> </html> Directory - backend |-- modeles | | -- orderModel.js | | -- ... other files | | |-- routes | | -- orderRoutes.js | | -- ... other files | | |-- views | | -- orders.hbs | | -- server.js | -- mailer.js | -- utils.js | ... other files - frontend | -- other directories
doc_23526861
My question is: is there even a point to having the node server listen for HTTP traffic as well? I guess what I'm unsure about is what percent of user clients' browsers support https or if there is any reason to allow http traffic. My app requires native websockets as well (requires >2011 browsers) so I'd imagine that all browsers past that would support https. Are there any instances or situations where clients can't use https and have to connect over http? Perhaps some mobile devices? What are the pros and cons towards listening for only https as opposed to opening up both port 80 and 443?
doc_23526862
function createChannel() { randomString = crypto.randomBytes(12).toString('hex'); const randomCategory = message.guild.channels.create(randomString, { type: 'category', permissionOverwrites: [ { id: message.guild.id, allow: ['VIEW_CHANNEL'], }, ], }); message.guild.channels.create(randomString, { type: 'text', parent: randomCategory.id, permissionOverwrites: [ { id: message.guild.id, allow: ['VIEW_CHANNEL'], }, ], }); message.guild.channels.create(randomString, { type: 'voice', parent: randomCategory.id, permissionOverwrites: [ { id: message.guild.id, allow: ['VIEW_CHANNEL'], }, ], }); } This should create a category, and populate it with a voice and text channel with the same name. However, when I run it the channels don't get their parent set correctly. A: According to the documentation, you should pass the channel as a parent instead of the id. You should probably also await the category creation before making the children. async function createChannel(){ const randomString = crypto.randomBytes(12).toString('hex'); //added const here since you're never overwriting const randomCategory = await message.guild.channels.create(randomString, { type: 'category', permissionOverwrites: [{ id: message.guild.id, allow: ['VIEW_CHANNEL'], }] }); await message.guild.channels.create(randomString, { type: 'text', parent: randomCategory, permissionOverwrites: [{ id: message.guild.id, allow: ['VIEW_CHANNEL'], }] }); await message.guild.channels.create(randomString, { type: 'voice', parent: randomCategory, permissionOverwrites: [{ id: message.guild.id, allow: ['VIEW_CHANNEL'], }] }); } A: guild.channels.create returns a promise so you either need to use the .then() method or async-await to get randomCategory. At the moment it's just a pending promise, not the returned category: // make the function an async function async function createChannel() { randomString = crypto.randomBytes(12).toString('hex'); // use await to wait the promise to resolve const randomCategory = await message.guild.channels.create(randomString, { type: 'category', permissionOverwrites: [ { id: message.guild.id, allow: ['VIEW_CHANNEL'], }, ], }); message.guild.channels.create(randomString, { type: 'text', // pass the randomCategory object, not just the id parent: randomCategory, permissionOverwrites: [ { id: message.guild.id, allow: ['VIEW_CHANNEL'], }, ], }); message.guild.channels.create(randomString, { type: 'voice', // pass the randomCategory object, not just the id parent: randomCategory, permissionOverwrites: [ { id: message.guild.id, allow: ['VIEW_CHANNEL'], }, ], }); } It seems to be working fine:
doc_23526863
The laptop shows a C# file in this way: The pc shows the same C# file in this other way: Obviously, I prefer the laptop version. But I can't get the PC to color the text in the same way. Any suggestion? A: VS Code comes with 2 dark and 2 light themes (Dark, Dark+, Light and Light+). On your laptop, the Dark+ theme is active, on your PC, it's the Dark theme. Changing the Theme In VS Code on your PC, press F1, enter Theme, select Preferences: Color Theme, select Dark+ from the dropdown and you should be fine. You can also press Ctrl+K, then Ctrl+T to open the theme dropdown.
doc_23526864
View: <%= form_tag :action => 'update_subject', :controller => 'task', :id => @task.id do -%> <tr> <td><b>Subject:</b></td> <td><div id='edit_subject_div'><%=text_field_tag 'subject', @task.subject %></div></td> </tr> <tr> <td></td> <td><%=submit_tag "Submit", data: { disable_with: "Please wait..."}%></td> </tr> <%end -%> Action: def update_subject @task = Task.find_by_id(params[:id]) if @task.subject != params[:subject] @task.subject = params[:subject] @task.save! end end Whole Form: <script> $(document).ready(function(){ $('select#activity_category_id').chained('select#cat_type_id'); $('#activity_category_id').css('border', 'Silver 1px solid'); $('#activity_location_id').css('border', 'Silver 1px solid'); $('#activity_location_modifier_id').css('border', 'Silver 1px solid'); //$('a[rel*=facebox]').facebox(); }); $(document).on('ajax:before', function(){ $.facebox.loading(); }); </script> <h2>Task Detail:</h2><br/> <% @task = Task.find(params[:task_id].to_i) if params[:task_id] @devices = [["",""]] + Device.where(job_id: @task.job_id, active: true).order(:name).pluck('name', 'id') @hours = (0..24).to_a @minutes = [0, 15, 30, 45] @today = Date.today @priorities = ["High", "Medium", "Low"] @user_list=[["",""]] + User.where(:active=>true).order('nickname').pluck('nickname', 'id') @groups=Group.order('name').pluck('name', 'id') @groups=@groups.each do |g| g[1]='group' + g[1].to_s end @users = @user_list + @groups @location=Location.where(active: true).order('description').pluck('description', 'id') @location_modifier=LocationModifier.where(active: true).order('description').pluck('description', 'id') #@categories = Category.where(active: 1).order(:description).pluck('description', 'id') params[:sort].nil? ? sort_str = "" : sort_str = params[:sort] params[:hist_length].nil? ? hist_str = "" : hist_str = params[:hist_length] @return_url = params[:return_url] %> <table style="border:none;width:90%"> <tr><td style="width:38%;vertical-align: top"> <table style="border:none;width:90%"> <tr><td><b>Task ID:</b></td> <td><%=@task.id.to_s%></td></tr> <tr> <td><b>Method of Contact:</b></td> <td><%= @task.contact_type %></td> </tr> <tr> <td><b>Contacted by:</b></td> <td><%= @task.customer_contact %></td> </tr> <tr> <td><b>Task Created by:</b></td> <td><%= @task.created_by.nickname %></td> </tr> <% if !@task.parent_task_id.nil? then %> <tr> <td><b>Task Split from:</b></td> <td><%= link_to 'Parent Task', :action => 'edit', :id => @task.parent_task_id %></td> </tr> <% end %> <%= form_for @task do |f|%> <tr> <td><b><%= f.label :subject %>:</b></td> <td><div id='edit_subject_div'><%= f.text_field :subject %></div></td> </tr> <tr> <td></td> <td><%= f.submit %></td> </tr> <%end %> <tr> <td colspan=2><b>Description:</b></td> </tr>c <tr> <td colspan=2><%=simple_format(@task.description)%></td> </tr> <tr><td colspan=2>&nbsp;</td></tr> <tr> <td><b>Task Initiated:</b></td> <td><%= @task.created_at.strftime("%H:%M %p %m/%d/%y") %>&nbsp;&nbsp;<%= (Date.today - @task.problem_on).to_i %> Days Old</td> </tr> <tr> <td><b>Assigned Due Date:</b></td> <td><%= @task.due_on.strftime("%m/%d/%y") %></td> </tr> <tr> <td><b>Status:</b></td> <td> <% if @task.resolved_on %> Resolved on <%= @task.resolved_on.strftime("%m/%d/%y") %> <% elsif @today < @task.due_on %> Due in <%= (@task.due_on - @today).to_i %> Days <% elsif @today > @task.due_on %> <%= (@today - @task.due_on).to_i %> Days Overdue <% else %> Due Today <% end %> </td> </tr> <tr> <td><b>Device:</b></td> <td><%= @task.device.nil? ? "None Assigned" : @task.device.name %></td> </tr> <tr> <td><b>Assigned To:</b></td> <% if !@task.assigned_to.nil? then %> <td><%=@task.assigned_to.nickname %></td> <% elsif !@task.group.nil? then %> <td><%=@task.group.name%></td> <% else %> <td>Unassigned</td> <% end %> </tr> <tr> <td><b>Priority:</b></td> <td><%=@task.priority %></td> </tr> <tr> <td><b>Resolved:</b></td> <% if !@task.resolved_on.nil? then %> <td><%=@task.resolved_on.strftime("%m/%d/%Y") %></td> <% else %> <td>Unresolved</td> <% end %> </tr> </table> <%=form_tag :action => 'update', :controller => 'task', :id => @task.id do -%><%=hidden_field_tag 'from_project_track', 'yes'%><%=hidden_field_tag 'return_path', @return_url%> <table> <tr><td colspan=2><b>New Note:</b></td></tr> <tr> <td colspan=2><%= text_area_tag 'note', nil, :size => '50x5' %></td> </tr> <% if !@task.device_id.nil? then %> <tr> <td><label for="task_device_id">Device</label>:</td> <td><%=select_tag 'task[device_id]', options_for_select(@devices, @task.device_id) %></td> <td>&nbsp;</td> </tr> <%else%> <tr> <td><label for="task_device_id">Device</label>:</td> <td><%=select_tag 'task[device_id]', options_for_select(@devices, '') %></td> <td>&nbsp;</td> </tr> <% end %> <tr> <td>Assigned Due Date:</td> <td><%= date_select 'task', 'due_on' %></td> <td>&nbsp;</td> </tr> <% if !@task.assigned_to_id.nil? then %> <tr> <td><label for="task_assigned_to">Assigned To</label>:</td> <td><%= select_tag 'task[assigned_to_id]', options_for_select(@users, :selected=>@task.assigned_to_id.to_s) %></td> <td>&nbsp;</td> </tr> <% elsif !@task.group_id.nil? then %> <tr> <td><label for="task_assigned_to">Assigned To</label>:</td> <td><%= select_tag 'task[assigned_to_id]', options_for_select(@users, 'group' + @task.group_id.to_s) %></td> <td>&nbsp;</td> </tr> <% else %> <tr> <td><label for="task_assigned_to">Assigned To</label>:</td> <td><%= select_tag 'task[assigned_to_id]', options_for_select(@users) %></td> <td>&nbsp;</td> </tr> <% end %> <tr> <td><label for="task_priority">Priority:</label></td> <td><%= select 'task', 'priority', @priorities %></td> <td>&nbsp;</td> </tr> <tr> <td>Resolved:</td> <td><%= check_box_tag 'resolved', 1, @task.resolved_on %></td> </tr> <tr> <td>Bill:</td> <td colspan="2"><%= select_tag 'bill_hours', options_for_select(@hours, 0) %>:<%= select_tag 'bill_minutes', options_for_select(@minutes, 0) %></td> </tr> <tr> <td>Nonbill:</td> <td colspan="2"><%= select_tag 'nonbill_hours', options_for_select(@hours, 0) %>:<%= select_tag 'nonbill_minutes', options_for_select(@minutes, 0) %></td> </tr> <tr> <td>Category:</td> <td colspan="2"> <%=select_tag 'cat_type_id',options_for_select(@cat_type_list,@selected_cat_type), {:prompt=>"Select Category Type"}%><br/> <select id="activity_category_id" prompt="Select Category" name="activity[category_id]" style="width:300px;"> <option value=''>Select Category</option> <%@cat_list.each do |c|%> <option value="<%=c.id%>" <%=(!@activity.nil? && @activity.category_id==c.id) ? "selected" : "" %> class="<%=c.cat_type_id.nil? ? '':c.cat_type_id%>"><%=c.short_description.nil? ? c.description : c.short_description%></option> <%end%> </select></td> </tr> <tr> <td>Location:</td> <td><%= select 'activity', 'location_id',[["",""]] + @location %></td> </tr> <tr> <td>Location Modifier:</td> <td><%= select 'activity', 'location_modifier_id',[["",""]] + @location_modifier %></td> </tr> <tr> <td>Review?:</td> <td colspan="2"><%= check_box 'activity', 'review' %></td> </tr> <tr> <td colspan=2 align="CENTER"><%=submit_tag "Submit", id: 'commit', data: { disable_with: "Please wait..."}%></td> </tr> </table> <% end -%> </td> <% if params[:mobile] == "1" then %> </tr> <tr> <% end %> <td valign="TOP"> <table style="width:90%;padding:0;"> <tr><td colspan="2" ><%=link_to 'Task Time Report', :controller=>'time', :action=>'list', :task_id=>@task.id %></td></tr> <tr><td colspan="2" align="LEFT"><b>Notes:</b></td></tr> <% @notes = Note.where(task_id: @task.id).order('created_at') %> <% @notes.each do |n| %> <tr style="background-color: <%=cycle("white","silver")%>;"><td valign="TOP"><b><%=n.created_by.nil? ? "Error" : n.created_by.nickname %><br>(<%=n.created_at.strftime("%m/%d/%Y %I:%M")%>)</b></td><td valign="TOP"><%=simple_format(n.content)%></td></tr> <% end %> </table> </td></tr> </table> A: Try using form_for since you are modifying an existing object @task: <%= form_for :task, @task, :url => { :action => :update_subject} do |f| %> <%= f.label :subject %>: <%= f.text_field :subject %> <%= f.submit %> <% end %> A: Remove the following line from the Javascript: $('form').submit(confirmSelections); This will no longer perform dynamic form validations, but should allow the Submit button to work. The real issue will be somewhere in the confirmSelections logic, and that will be dependent on what data has been entered on the form. As a side note, this code looks like it would need some serious rework. At a minimum: * *Use form_for instead of form_tag *Use f.submit instead of submit_tag (once the form_for is implemented) *All of the Javascript is static, and should be moved into the assets pipeline, rather than be included inline *All of the Ruby code in the block immediately following <h2>Task Detail:</h2> should be moved to the controller/action *The code for @notes = Note.where(task_id: @task.id).order('created_at') should be moved to the controller/action *The Javascript should select CSS classes, not explicit CSS styling, so that your presentation is able to be easily maintained These should actually help make this template reasonably maintainable and separate the MVC concerns from one another. A: Not Sure why or how this fixed it but i removed the first form and made the second form cover the whole view. The downside to this is I have to submit the whole page in order to update the subject. <script> $(document).ready(function(){ $('select#activity_category_id').chained('select#cat_type_id'); $('#activity_category_id').css('border', 'Silver 1px solid'); $('#activity_location_id').css('border', 'Silver 1px solid'); $('#activity_location_modifier_id').css('border', 'Silver 1px solid'); //$('a[rel*=facebox]').facebox(); }); $(document).on('ajax:before', function(){ $.facebox.loading(); }); function confirmSelections(){ valid=false; valid1=false; valid2=false; if ($('#activity_category_id').val()==""){ $('#activity_category_id').css('border', 'red 2px solid'); valid= false; }else{ $('#activity_category_id').css('border', 'Silver 1px solid'); valid= true; } if ($('#activity_location_id').val()=="") { $('#activity_location_id').css('border', 'red 2px solid'); valid1=false; } else {$('#activity_location_id').css('border', 'Silver 1px solid'); valid1=true;} if ($('#activity_location_modifier_id').val()=="") {$('#activity_location_modifier_id').css('border', 'red 2px solid'); valid2=false; }else{ $('#activity_location_modifier_id').css('border', 'Silver 1px solid'); valid2= true; } if (valid && valid1 && valid2) {return true;} else { if (($('#nonbill_hours').val()!='0' || $('#bill_hours').val()!='0' || $('#nonbill_minutes').val()!='0' || $('#bill_minutes').val()!='0' || $('#nonbill_hours').val()!='0') && ($('#activity_category_id').val()=='')){ var answer = (confirm('No category is selected. Click Cancel to select. Click OK to update the task with no time entry.')) ; return answer; } if (($('#nonbill_hours').val()!='0' || $('#bill_hours').val()!='0' || $('#nonbill_minutes').val()!='0' || $('#bill_minutes').val()!='0' || $('#nonbill_hours').val()!='0') && ($('#activity_location_id').val()=='')){ var answer = (confirm('No location is selected. Click Cancel to select. Click OK to update the task with no time entry.')) ; return answer; } if (($('#nonbill_hours').val()!='0' || $('#bill_hours').val()!='0' || $('#nonbill_minutes').val()!='0' || $('#bill_minutes').val()!='0' || $('#nonbill_hours').val()!='0') && ($('#activity_location_modifier_id').val()=='')){ var answer = (confirm('No location modifier is selected. Click Cancel to select. Click OK to update the task with no time entry.')) ; return answer; } } } $('form').submit(confirmSelections); </script> <h2>Task Detail:</h2><br/> <% @task = Task.find(params[:task_id].to_i) if params[:task_id] @devices = [["",""]] + Device.where(job_id: @task.job_id, active: true).order(:name).pluck('name', 'id') @hours = (0..24).to_a @minutes = [0, 15, 30, 45] @today = Date.today @priorities = ["High", "Medium", "Low"] @user_list=[["",""]] + User.where(:active=>true).order('nickname').pluck('nickname', 'id') @groups=Group.order('name').pluck('name', 'id') @groups=@groups.each do |g| g[1]='group' + g[1].to_s end @users = @user_list + @groups @location=Location.where(active: true).order('description').pluck('description', 'id') @location_modifier=LocationModifier.where(active: true).order('description').pluck('description', 'id') #@categories = Category.where(active: 1).order(:description).pluck('description', 'id') params[:sort].nil? ? sort_str = "" : sort_str = params[:sort] params[:hist_length].nil? ? hist_str = "" : hist_str = params[:hist_length] @return_url = params[:return_url] %> <table style="border:none;width:90%"> <tr><td style="width:38%;vertical-align: top"> <%=form_tag :action => 'update', :controller => 'task', :id => @task.id do -%><%=hidden_field_tag 'from_project_track', 'yes'%><%=hidden_field_tag 'return_path', @return_url%> <table style="border:none;width:90%"> <tr><td><b>Task ID:</b></td> <td><%=@task.id.to_s%></td></tr> <tr> <td><b>Method of Contact:</b></td> <td><%= @task.contact_type %></td> </tr> <tr> <td><b>Contacted by:</b></td> <td><%= @task.customer_contact %></td> </tr> <tr> <td><b>Task Created by:</b></td> <td><%= @task.created_by.nickname %></td> </tr> <% if !@task.parent_task_id.nil? then %> <tr> <td><b>Task Split from:</b></td> <td><%= link_to 'Parent Task', :action => 'edit', :id => @task.parent_task_id %></td> </tr> <% end %> <tr> <td><b>Subject:</b></td> <td><div id='edit_subject_div'><%= text_field_tag 'task[subject]', @task.subject%></div></td> </tr> <tr> <td colspan=2><b>Description:</b></td> </tr> <tr> <td colspan=2><%=simple_format(@task.description)%></td> </tr> <tr><td colspan=2>&nbsp;</td></tr> <tr> <td><b>Task Initiated:</b></td> <td><%= @task.created_at.strftime("%H:%M %p %m/%d/%y") %>&nbsp;&nbsp;<%= (Date.today - @task.problem_on).to_i %> Days Old</td> </tr> <tr> <td><b>Assigned Due Date:</b></td> <td><%= @task.due_on.strftime("%m/%d/%y") %></td> </tr> <tr> <td><b>Status:</b></td> <td> <% if @task.resolved_on %> Resolved on <%= @task.resolved_on.strftime("%m/%d/%y") %> <% elsif @today < @task.due_on %> Due in <%= (@task.due_on - @today).to_i %> Days <% elsif @today > @task.due_on %> <%= (@today - @task.due_on).to_i %> Days Overdue <% else %> Due Today <% end %> </td> </tr> <tr> <td><b>Device:</b></td> <td><%= @task.device.nil? ? "None Assigned" : @task.device.name %></td> </tr> <tr> <td><b>Assigned To:</b></td> <% if !@task.assigned_to.nil? then %> <td><%=@task.assigned_to.nickname %></td> <% elsif !@task.group.nil? then %> <td><%=@task.group.name%></td> <% else %> <td>Unassigned</td> <% end %> </tr> <tr> <td><b>Priority:</b></td> <td><%=@task.priority %></td> </tr> <tr> <td><b>Resolved:</b></td> <% if !@task.resolved_on.nil? then %> <td><%=@task.resolved_on.strftime("%m/%d/%Y") %></td> <% else %> <td>Unresolved</td> <% end %> </tr> </table> <table> <tr><td colspan=2><b>New Note:</b></td></tr> <tr> <td colspan=2><%= text_area_tag 'note', nil, :size => '50x5' %></td> </tr> <% if !@task.device_id.nil? then %> <tr> <td><label for="task_device_id">Device</label>:</td> <td><%=select_tag 'task[device_id]', options_for_select(@devices, @task.device_id) %></td> <td>&nbsp;</td> </tr> <%else%> <tr> <td><label for="task_device_id">Device</label>:</td> <td><%=select_tag 'task[device_id]', options_for_select(@devices, '') %></td> <td>&nbsp;</td> </tr> <% end %> <tr> <td>Assigned Due Date:</td> <td><%= date_select 'task', 'due_on' %></td> <td>&nbsp;</td> </tr> <% if !@task.assigned_to_id.nil? then %> <tr> <td><label for="task_assigned_to">Assigned To</label>:</td> <td><%= select_tag 'task[assigned_to_id]', options_for_select(@users, :selected=>@task.assigned_to_id.to_s) %></td> <td>&nbsp;</td> </tr> <% elsif !@task.group_id.nil? then %> <tr> <td><label for="task_assigned_to">Assigned To</label>:</td> <td><%= select_tag 'task[assigned_to_id]', options_for_select(@users, 'group' + @task.group_id.to_s) %></td> <td>&nbsp;</td> </tr> <% else %> <tr> <td><label for="task_assigned_to">Assigned To</label>:</td> <td><%= select_tag 'task[assigned_to_id]', options_for_select(@users) %></td> <td>&nbsp;</td> </tr> <% end %> <tr> <td><label for="task_priority">Priority:</label></td> <td><%= select 'task', 'priority', @priorities %></td> <td>&nbsp;</td> </tr> <tr> <td>Resolved:</td> <td><%= check_box_tag 'resolved', 1, @task.resolved_on %></td> </tr> <tr> <td>Bill:</td> <td colspan="2"><%= select_tag 'bill_hours', options_for_select(@hours, 0) %>:<%= select_tag 'bill_minutes', options_for_select(@minutes, 0) %></td> </tr> <tr> <td>Nonbill:</td> <td colspan="2"><%= select_tag 'nonbill_hours', options_for_select(@hours, 0) %>:<%= select_tag 'nonbill_minutes', options_for_select(@minutes, 0) %></td> </tr> <tr> <td>Category:</td> <td colspan="2"> <%=select_tag 'cat_type_id',options_for_select(@cat_type_list,@selected_cat_type), {:prompt=>"Select Category Type"}%><br/> <select id="activity_category_id" prompt="Select Category" name="activity[category_id]" style="width:300px;"> <option value=''>Select Category</option> <%@cat_list.each do |c|%> <option value="<%=c.id%>" <%=(!@activity.nil? && @activity.category_id==c.id) ? "selected" : "" %> class="<%=c.cat_type_id.nil? ? '':c.cat_type_id%>"><%=c.short_description.nil? ? c.description : c.short_description%></option> <%end%> </select></td> </tr> <tr> <td>Location:</td> <td><%= select 'activity', 'location_id',[["",""]] + @location %></td> </tr> <tr> <td>Location Modifier:</td> <td><%= select 'activity', 'location_modifier_id',[["",""]] + @location_modifier %></td> </tr> <tr> <td>Review?:</td> <td colspan="2"><%= check_box 'activity', 'review' %></td> </tr> <tr> <td colspan=2 align="CENTER"><%=submit_tag "Submit", id: 'commit', data: { disable_with: "Please wait..."}%></td> </tr> </table> <% end -%> </td> <% if params[:mobile] == "1" then %> </tr> <tr> <% end %> <td valign="TOP"> <table style="width:90%;padding:0;"> <tr><td colspan="2" ><%=link_to 'Task Time Report', :controller=>'time', :action=>'list', :task_id=>@task.id %></td></tr> <tr><td colspan="2" align="LEFT"><b>Notes:</b></td></tr> <% @notes = Note.where(task_id: @task.id).order('created_at') %> <% @notes.each do |n| %> <tr style="background-color: <%=cycle("white","silver")%>;"><td valign="TOP"><b><%=n.created_by.nil? ? "Error" : n.created_by.nickname %><br>(<%=n.created_at.strftime("%m/%d/%Y %I:%M")%>)</b></td><td valign="TOP"><%=simple_format(n.content)%></td></tr> <% end %> </table> </td></tr> </table>
doc_23526865
type Server struct { Etcd [] struct { CertCn string `json:"cert_cn"` } `json:"etcd"` } type CertExpiryReport struct { Data struct { Servers map[string]*Server } `json:"data"` Summary struct { Expired int `json:"expired"` Ok int `json:"ok"` Total int `json:"total"` Warning int `json:"warning"` } `json:"summary"` } The following is the JSON content. { "data": { "myserver1.mydomain1.org": { "etcd": [ { "cert_cn": "CN:something" } ] } "myserver2.mydomain2.org": { "etcd": [ { "cert_cn": "CN:something" } ] } }, "summary": { "expired": 0, "ok": 31, "total": 31, "warning": 0 } } This is my code. func printStuff() { bytes, err := ioutil.ReadFile(jsonFile) if err != nil { log.Errorf("%s", err.Error()) os.Exit(1) } var certExpiryReport CertExpiryReport err = json.Unmarshal(bytes, &certExpiryReport) if err != nil { log.Errorf("%s", err.Error()) os.Exit(1) } log.Info(certExpiryReport) } The output is the following. I am not getting any errors. {{map[]} {0 31 31 0}} Why can't GO parse the JSON? Is something wrong with my structs? A: There is something wrong with the struct (or JSON). CertExpiryReport struct has additional level of nesting in Data field. Try to replace Data struct { Servers map[string]*Server } `json:"data"` With Data map[string]*Server `json:"data"` Also, your JSON gives me error (you forgot comma after first server description). Here is working test with change to your structs and JSON: https://play.golang.org/p/QwnHGc9MElb Other way would be to put inside JSON "data" field "servers" field, and store content of data there. If you need more nesting.
doc_23526866
The sample application is very simple (it is part of GTSAM) but when I run it, I am getting this linker error: Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol __imp_clock referenced in function gk_CPUSeconds example D:\MyData\SourceCode\gtsam_win\cmake\example_cmake_find_gtsam\build\metis-gtsamDebug.lib(timers.obj) and Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol __imp__time64 referenced in function time example D:\MyData\SourceCode\gtsam_win\cmake\example_cmake_find_gtsam\build\metis-gtsamDebug.lib(timers.obj) 1 a search showed me that these two functions are part of MSVC libraries and they should in linked to the system. How can I fix the issue? It seems that the problem is mis match between the setting during library build and application build, but I can not find any linker setting different. Where to look for any such difference? A: __imp_ prefix in unresolved external runtime library symbol from the linked library means the library was built with DLL runtime (/MD in C++ -> Code Generation -> Runtime Library). If you build the application with static runtime (/MT) the symbols from the DLL runtime will be unresolved. Runtime settings should be the same for all compilation units.
doc_23526867
private double d = 1000; private boolean b; private final int f = 100; private char c = 'c'; so if the parameter is one of the above the method should return only d, b, f or c. How is algorithms should be implemented. I have tried to use regex to strip the word after the types but it became very complicated. Can anyone give me some clues, thanks A: try this String type = str.replaceAll(".*\\s(.)\\s*=.*", "$1"); A: You can take the string before the equal sign without regex: public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(true){ String theString = sc.nextLine(); String left = theString.split("=")[0].trim(); // Split into variable part and value part int lastSpace = left.lastIndexOf(" "); // there must be a space before a variable declaration, take the index String variableName = left.substring(lastSpace+1); // take the variable name System.out.println(variableName); } } If you're implementing this on Python, it's much easier: the_string = 'private double d = 1000;' print the_string.split('=',1)[0].strip().rsplit(' ',1)[1]
doc_23526868
Currently I'm inserting some items into the db in a for-loop, but if I make a one sql-query out of the inserts and insert them at the end of the process, this would help me reduce the time that is needed to connect to the MySQL db, since there is no need to make a new connection for each item. Problem: I need the auto increment id's from those inserts. Now I can get them with the lastInsertId() -function, but only when I insert them one by one. Question1: Is it even possible to get all the AI-id's from a multiple row -insert? Question2: If it's not possible to get the id's from a multi-row-insert, is it possible to keep the connection open as long as all the items has been saved? Maybe1...: I thought that maybe I could get the last insert id of the multi-row-insert, and then calculate the other id's based on how many inserts I made. But I'm not sure how the mysql actually works. If there are many other connections, is there a possibility that the other connections get some of the AI values that should belong to our current connection? This would end up in a situation where I should have id's: 1, 2, 3, but other connection stole some of these and we end up having: 1, 3, 5, and thus, the calculating won't work. I'm not an expert with the MySQL, and I cannot find a decent explanation of this in the docs. Maybe2...: I was also thinking that if all else fails, I could get the just inserted id's with a SELECT -query. This could be faster than the original way if there are more than 2 items to be inserted. Or could it? The math would be that I insert 3 items in a one query and get the just inserted id's with one, VS I insert 3 items in 3 queries. But when would this be meaningless optimization and when an actual time saving feature? Conditions: I'm using Symfony2 -framework and Doctrine DBAL for the connections. One item has 20 columns worth of data. 1/3 of the columns are TINYINTs, 1/3 are VARCHARS of varying lengths but usually we are talking about short strings of 5-15 chars. And 1/3 of the columns are INT's and DOUBLE's that are small values as well. There can be anything of 1 to 60 items to be inserted at a time. I think about 90% of the inserts have around 1-6 items in a one session. Update: I've been testing this out and it seems that the DBAL doesn't close the connection but re-uses the already created connections by default. This is good. I also tested the inserting of multiple items in one query VS inserting them one at a time. Results are not what I expected.. It didn't matter how many items I inserted, but the time it took was roughly the same. This sparks up a question: why? One might think that 100 inserts individually is slower than one insert with 100 rows, but this didn't seem to be the case. Does anyone have any insights on this behaviour? Why doesn't it work like I thought it would?
doc_23526869
Here, I'm trying to add a node on tap... but I couldn't figure out how to get the specific coordinates to pass to the rendererPosition property of the new node. cy.on('tap', function (e) { if (e.cyTarget === cy) { //var pos = $(this).position().left, //tried this, as jquery //posY = $(this).position().top; //positioning without success var idNum = cy.nodes().size(); var setID = idNum.toString(); cy.add([{ group: "nodes", data: { id: "n" + setID }, renderedPosition: { x: e.pageX, //- posX, y: e.pageY //- posY }, }]); } }); Using the same code but binding with the $('#cy').click function, it works... but with cy.on('tap') way, the event e doesn't have the pageX and pageY properties, neither can I get the element position using the $(this).position() function. I really prefer using tap, as I'm trying to develop my application also for mobile interfaces. Thanks in advance. EDIT: Using @darshanags observation and this link, I solved this way: var idNum = cy.nodes().size(), setID = idNum.toString(), offset = $("cy").offset(), position = { x: e.originalEvent.x - offset.left, y: e.originalEvent.y - offset.top }; cy.add([{ group: "nodes", data: { id: "n" + setID }, renderedPosition: { x: position.x, y: position.y }, ... }]); A: Your usage of is incorrect, Cytoscape's .position() works a bit differently to jQuery's position(): Get the position and use it: var idNum = cy.nodes().size(), setID = idNum.toString(), position = { x: e.cyTarget.position("x"), y: e.cyTarget.position("y") }; cy.add([{ group : "nodes", data : { id : "n" + setID }, renderedPosition : { x : position.x, y : position.y } }]); Docs: http://cytoscape.github.io/cytoscape.js/#collection/position--dimensions/node.position A: I answered this elsewhere, but had come across both these questions while trying to make this work, so I'll post it here, too. In cytoscape.js 3.2, there are convenience functions for this: cy.on("tap", function(e) { cy.add([{ group: "nodes", id: "testid", renderedPosition: { x: e.renderedPosition.x, y: e.renderedPosition.y, }, }); }); This ends up being equivalent to (assuming you've set container: $("#cy-container")): cy.on("tap", function(e) { let canvas = $("#cy-container").find("canvas").get(0); cy.add([{ group: "nodes", id: "testid", renderedPosition: { x: e.originalEvent.pageX - $(canvas).offset().left, y: e.originalEvent.pageY - $(canvas).offset().top, }, }); });
doc_23526870
doc_23526871
I have an Excel document where from cell A to L I have a block of data. Row A has the name of an item, Row G has the items' price As you can see, the items are unordered in the table, is it possible to get every line where A = Item1 and then use that to get all the prices? G A: The simplest way to achieve that would be to just set a filter - Set the cursor to the header row, and select Data -- Filter. Then you can filter to your hearts content. (Consider adding the header row if you don't have one) Another way to achieve the same functionality is to select Home -- "Format as Table". Confusing name, but a bit more versatile.
doc_23526872
I want to search by name, which is in the en or in any another language which is supported by column. Table: places ------- id ascii_name translations dsrsfdsf be-namor { "en":{"locale":"en","name":"Namur"},"de":{"locale":"de","name":"Namur"},"bg":{"locale":"bg","name":"Намюр"} } s3drs2es be-mouscron { "en":{"locale":"en","name":"Mouscron"},"pl":{"locale":"pl","name":"Mouscron"},"de":{"locale":"de","name":"Mouscron"} } I've just found a way using json_object_keys, but it causes an error that I can't use set-returning function in WHERE statement. SELECT * FROM places p WHERE p.translations->json_object_keys(p.translations)->'name' LIKE '%Namur%' Error: [0A000] ERROR: set-returning functions are not allowed in WHERE Thank you in advance! A: so=# with c(j) as (values ('{ "en":{"locale":"en","name":"Namur"},"de":{"locale":"de","name":"Namur"},"bg":{"locale":"bg","name":"Намюр"} }'::json) ,('{ "en":{"locale":"en","name":"Mouscron"},"pl":{"locale":"pl","name":"Mouscron"},"de":{"locale":"de","name":"Mouscron"} }') ) , filter as (select j,j->json_object_keys(j)->>'name' like '%amur%' as "found" from c) select distinct j::jsonb from filter where found; j ----------------------------------------------------------------------------------------------------------------------------- {"bg": {"name": "Намюр", "locale": "bg"}, "de": {"name": "Namur", "locale": "de"}, "en": {"name": "Namur", "locale": "en"}} (1 row) mind I cast json to jsonb to filter out dupes
doc_23526873
More concise: createFoo(): Observable<Foo> { return this.step1() .flatMap((result: Bar) => { const processedResult = { ..., result } return this.step2(processedResult) }); } More readable: createFoo(): Observable<Foo> { return this.step1() .map((result: Bar) => { const processedResult = { ..., result } return processedResult; }) .flatMap((processedResult: any) => { return this.step2(processedResult); }) .map((result: Foo) => { return result; }); } The first variant only uses one mapping function and is generally a lot less noisy, but I also find it more difficult to tell at a glance what's actually happening. It also seems like it wouldn't scale well if I had more than two observables that needed to be chained. The second variant is more noisy, with three times the function calls, but I also find it better at explaining what types are output where and how data is processed over the course of the stream. It also makes it much clearer how flatMap differs from the regular map, which is something I've had some trouble keeping my understanding straight on. Is there a convention with RxJs that favors one or the other? Or is it personal preference?
doc_23526874
I initialize a room object from Room class with property map of type ArrayList like this: Room room1 = new Room() { map = new ArrayList { new ArrayList(new int[] { 1, 1 } ), new ArrayList(new int[] { 1, 1 } ), new ArrayList(new int[] { 1, 1 } ) } } Then I override ToString() method of the class Room public override string ToString() { return "Room ["+map.Count+","+map[0].Count+"]"; } Debug.Log(room1); results in error: 'object' does not contain a definition for 'Count' and no accessible extension method 'Count' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) if I change ToString override as follows: { return "Room ["+map.Count+","+map[0]+"]"; } then the result of Debug.Log(room1); is "Room [3,System.Collections.ArrayList]" thus I came to conclusion that I get the error: System.Collections.ArrayList does not contain a definition for 'Count' What is going on?
doc_23526875
public event EventHandler SomeEvent; ... { .... if(SomeEvent!=null)SomeEvent(); } In a multi-threaded environment, how does this code guarantee that another thread will not alter the invocation list of SomeEvent between the check for null and the invocation of the event? A: As you point out, where multiple threads can access SomeEvent simultaneously, one thread could check whether SomeEventis null and determine that it isn't. Just after doing so, another thread could remove the last registered delegate from SomeEvent. When the first thread attempts to raise SomeEvent, an exception will be thrown. A reasonable way to avoid this scenario is: protected virtual void OnSomeEvent(EventArgs args) { EventHandler ev = SomeEvent; if (ev != null) ev(this, args); } This works because whenever a delegate is added to or removed from an event using the default implementations of the add and remove accessors, the Delegate.Combine and Delegate.Remove static methods are used. Each of these methods returns a new instance of a delegate, rather than modifying the one passed to it. In addition, assignment of an object reference in .NET is atomic, and the default implementations of the add and remove event accessors are synchronised. So the code above succeeds by first copying the multicast delegate from the event to a temporary variable. Any changes to SomeEvent after this point will not affect the copy you've made and stored. Thus you can now safely test whether any delegates were registered and subsequently invoke them. Note that this solution solves one race problem, namely that of an event handler being null when it's invoked. It doesn't handle the problem where an event handler is defunct when it's invoked, or an event handler subscribes after the copy is taken. For example, if an event handler depends on state that's destroyed as soon as the handler is un-subscribed, then this solution might invoke code that cannot run properly. See Eric Lippert's excellent blog entry for more details. Also, see this StackOverflow question and answers. EDIT: If you're using C# 6.0, then Krzysztof's answer looks like a good way to go. A: The recommended way is a little different and uses a temporary as follows: EventHandler tmpEvent = SomeEvent; if (tmpEvent != null) { tmpEvent(); } A: Safer approach: public class Test { private EventHandler myEvent; private object eventLock = new object(); private void OnMyEvent() { EventHandler handler; lock(this.eventLock) { handler = this.myEvent; } if (handler != null) { handler(this, EventArgs.Empty); } } public event MyEvent { add { lock(this.eventLock) { this.myEvent += value; } } remove { lock(this.eventLock) { this.myEvent -= value; } } } } -bill A: In C# 6.0 you can use monadic Null-conditional operator ?. to check for null and raise events in easy and thread-safe way. SomeEvent?.Invoke(this, args); It’s thread-safe because it evaluates the left-hand side only once, and keeps it in a temporary variable. You can read more here in part titled Null-conditional operators. A: The simplest way remove this null check is to assign the eventhandler to an anonymous delegate. The penalty incurred in very little and relieves you of all the null checks, race conditions etc. public event EventHandler SomeEvent = delegate {}; Related question: Is there a downside to adding an anonymous empty delegate on event declaration? A: I would like to suggest an slight improvment to RoadWarrior's answer by utilizing an extention function for the EventHandler: public static class Extensions { public static void Raise(this EventHandler e, object sender, EventArgs args = null) { var e1 = e; if (e1 != null) { if (args == null) args = new EventArgs(); e1(sender, args); } } } With this extension in scope, events can be raised simply by: class SomeClass { public event EventHandler MyEvent; void SomeFunction() { // code ... //--------------------------- MyEvent.Raise(this); //--------------------------- } } c# events
doc_23526876
1.Add cordova-uglify plugin 2.Remove Splashscreen 3.Minify my html,css,js and use svg instead of png but my app size still 1.8MB How can I reduce My App Size further? I think its all due to google play service and admob
doc_23526877
1.setSupportActionBar(toolbar); 2.getSupportActionBar().setDisplayHomeAsUpEnabled(true); The snippet of code is: Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Comments"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); A: you can reach the app bar(action bar) via the toolbar . you make a toolbar and design it however you like then change the style of app to no action bar, then in code set you toolbar as actionbar. then your design toolbar will be the app bar A: Just an example. Use an Activity with this theme: <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar"> and this layout: <androidx.coordinatorlayout.widget.CoordinatorLayout> <com.google.android.material.appbar.MaterialToolbar android:id="@+id/toolbar"/> </androidx.coordinatorlayout.widget.CoordinatorLayout> Then just use: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } It is the result. Just an empty Toolbar. Add the setSupportActionBar(toolbar); override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar)) } This method sets the toolbar as the app bar for the activity Now add getSupportActionBar().setDisplayHomeAsUpEnabled(true); override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar)) supportActionBar.setDisplayHomeAsUpEnabled(true) } This method set whether home should be displayed as an "up" affordance
doc_23526878
For example, if I open a simple webpage, open Inspect Element, and change things like text inside paragraphs and headings, the changes are immediately reflected on the webpage and stay as long as I don't reload the page. Similarly, I tried to do some changes to the JavaScript code (Really simple code that does not connect to any server), but the changes did not take effect (What I did was edit the function a button activated so it did document.write() instead of displaying text in a blank paragraph element) I'm fairly sure this is possible to do, and I'm missing out on something. I am fully aware I can just save the webpage and do whatever I want with it's code, but I'm just seeing if I can do it this way as well. A: You can inject javascript methods via the console. That will have the same effect and will also allow you to copy / paste the new methods in fairly easily, instead of manually editing a JS file each time you refresh the page. As an example, open the console and paste the following in (on this page): $('p').on('click', function(){alert("clicked paragraph")}); Now click on a paragraph and you will see the alert. A: Of course, you can. Open "Sources" tab in your developer tools. Then, find your file in the sources tree on the left side. Select a file, edit it and save it using Ctrl+S, Chrome will substitute the original file with yours. You can also click {} icon in the bottom to prettify JS and make it easier to edit and debug. Note that it works only with .js files. You cannot modify inline scripts using this approach.
doc_23526879
fig, ax = plt.subplots(1, figsize = (10,10)) #Create the grid (different grid spacing): X = np.arange(0,10.01,0.25) Y = np.arange(0,10.01,1.00) #Create the 2D array to be plotted Z = [] for i in range(np.size(X)): Zaux = [] for j in range(np.size(Y)): Zaux.append(i*j + j) ax.scatter(X[i],Y[j], color = 'red', s = 0.25) Z.append(Zaux) #Mesh the 1D grids: Ymesh, Xmesh = np.meshgrid(Y, X) #Plot the color plot: ax.pcolor(Y,X, Z, cmap='viridis', vmin=np.nanmin(Z), vmax=np.nanmax(Z)) #Plot the points in the grid of the color plot: for i in range(np.size(X)): for j in range(np.size(Y)): ax.scatter(Y[j],X[i], color = 'red', s = 3) #Create a set of lines: for i in np.linspace(0,2,5): X_line = np.linspace(0,10,256) Y_line = i*X_line*3.1415-4 #Plot each line: ax.plot(X_line,Y_line, color = 'blue') ax.set_xlim(0,10) ax.set_ylim(0,10) plt.show() That outputs this graph: I need to find the closest points in Z that are being crossed by each of the lines. The idea is to integrate the values in Z that are crossed by the blue lines and plot that as a function of slope of the lines. Anyone has a good solution for it? I've tried a set of for loops, but I think it's kind of clunky. Anyway, thanks for your time... A: I am not sure about the closest points thing. That seems "clunky" too. What if it passes exactly in the middle between two points? Also I already had written code that weighs the four neighbor pixels by their closeness for an other project so I am going with that. Also I take the liberty of not rescaling the picture. i,j = np.meshgrid(np.arange(41),np.arange(11)) Z = i*j + j class Image_knn(): def fit(self, image): self.image = image.astype('float') def predict(self, x, y): image = self.image weights_x = [1-(x % 1), x % 1] weights_y = [1-(y % 1), y % 1] start_x = np.floor(x).astype('int') start_y = np.floor(y).astype('int') return sum([image[np.clip(np.floor(start_x + x), 0, image.shape[0]-1).astype('int'), np.clip(np.floor(start_y + y), 0, image.shape[1]-1).astype('int')] * weights_x[x]*weights_y[y] for x,y in itertools.product(range(2),range(2))]) And a little sanity check it returns the picture if we give it it's coordinates. image_model = Image_knn() image_model.fit(Z) assert np.allclose(image_model.predict(*np.where(np.ones(Z.shape, dtype='bool'))).reshape((11,41)), Z) I generate m=100 lines and scale the points on them so that they are evenly spaced. Here is a plot of every 10th of them. n = 1000 m = 100 slopes = np.linspace(1e-10,10,m) t, slope = np.meshgrid(np.linspace(0,1,n), slopes) x_max, y_max = Z.shape[0]-1, Z.shape[1]-1 lines_x = t lines_y = t*slope scales = np.broadcast_to(np.stack([x_max/lines_x[:,-1], y_max/lines_y[:,-1]]).min(axis=0), (n,m)).T lines_x *= scales lines_y *= scales And finally I can get the "points" consisting of slope and "integral" and draw it. You probably should take a closer look at the "integral" it's just a ruff guess of mine. %%timeit points = np.array([(slope, np.mean(image_model.predict(lines_x[i],lines_y[i])) *np.linalg.norm(np.array((lines_x[i,-1],lines_y[i,-1])))) for i,slope in enumerate(slopes)]) plt.scatter(points[:,0],points[:,1]) Notice the %%timeit in the last block. This takes ~38.3 ms on my machine and therefore wasn't optimized. As Donald Knuth puts it "premature optimization is the root of all evil". If you were to optimize this you would remove the for loop, shove all the coordinates for line points in the model at once by reshaping and reshaping back and then organize them with the slopes. But I saw no reason to put myself threw that for a few ms. And finally we get a nice cusp as a reward. Notice that it makes sense that the maximum is at 4 since the diagonal is at a slope of 4 for our 40 by 10 picture. The intuition for the cusp is a bit harder to explain but I guess you probably have that already. For the length it comes down to the function (x,y) -> sqrt(x^2+y^2) having different directional differentials when going up and when going left on the rectangle.
doc_23526880
Python has accuracy problems for large numbers, but if one simply rounds a logarithm to its floor, then it's possible to have a very simple implementation. I'd rather not code my own, so I'm looking for one. As an example for Java, Guava implements a very fast log10 function when you want to round to floor. A: If you only need to work with integers, there's always this slow-but-simple method: def log10floor(x): return len("%d" % x) - 1
doc_23526881
and similarly an IP Address as well? Thank you A: A MAC address is already in hexadecimal format, it is of the form of 6 pairs of 2 hexadecimal digits. String macAddress = "AA:BB:CC:DD:EE:FF"; String[] macAddressParts = macAddress.split(":"); // convert hex string to byte values Byte[] macAddressBytes = new Byte[6]; for(int i=0; i<6; i++){ Integer hex = Integer.parseInt(macAddressParts[i], 16); macAddressBytes[i] = hex.byteValue(); } And... String ipAddress = "192.168.1.1"; String[] ipAddressParts = ipAddress.split("\\."); // convert int string to byte values Byte[] ipAddressBytes = new Byte[4]; for(int i=0; i<4; i++){ Integer integer = Integer.parseInt(ipAddressParts[i]); ipAddressBytes[i] = integer.byteValue(); } A: The open-source IPAddress Java library will parse both MAC addresses and IP addresses, and convert to bytes in a polymorphic manner. Disclaimer: I am the project manager of that library. The following code will do what you are requesting: String ipv4Addr = "1.2.3.4"; String ipv6Addr = "aaaa:bbbb:cccc:dddd::"; String macAddr = "a:b:c:d:e:f"; try { HostIdentifierString addressStrings[] = { new IPAddressString(ipv4Addr), new IPAddressString(ipv6Addr), new MACAddressString(macAddr) }; Address addresses[] = new Address[addressStrings.length]; for(int i = 0; i < addressStrings.length; i++) { addresses[i] = addressStrings[i].toAddress();//parse } for(Address addr : addresses) { byte bytes[] = addr.getBytes(); //convert to a list of positive Integer for printing List<Integer> forPrinting = IntStream.range(0, bytes.length).map(idx -> 0xff & bytes[idx]).boxed().collect(Collectors.toList()); System.out.println("bytes for " + addr + " are " + forPrinting); } } catch(HostIdentifierException | IOException e) { //e.getMessage has validation error } output: bytes for 1.2.3.4 are [1, 2, 3, 4] bytes for aaaa:bbbb:cccc:dddd:: are [170, 170, 187, 187, 204, 204, 221, 221, 0, 0, 0, 0, 0, 0, 0, 0] bytes for 0a:0b:0c:0d:0e:0f are [10, 11, 12, 13, 14, 15]
doc_23526882
Please run this script in IE and Firefox (I make a test in IE 11 and Firefox 44.0.2.): LINK <div class="dropdown"> <select class="dropdown-select" onchange="if (this.value) window.location.href=this.value"> <option value="#">Wybierz swoją szkółkę</option> <option value="http://xxx">1</option> <option value="http://xxx">2</option> <option value="http://xxx">3</option> <option value="http://xxx">4</option> <option value="http://xxx">5</option> <option value="http://xxx">6</option> </select> </div> select option:nth-child(5){ display:none; color:red; } I want to hide 5th option. A: Thx for help! My solution: var elem = document.getElementById("divid"); elem.parentNode.removeChild(elem);
doc_23526883
I have what looks to me like appropriate object registration: For<ISomeInterface>().Use(() => GetConcreteInstance()); For<ISomeInterface>().MissingNamedInstanceIs.TheDefault(); For<ISomeOtherThing>().Add<OtherConcreteClass>() .Ctor<ISomeInterface>().IsNamedInstance("Special"); However, if no "Special" instance of ISomeInterface is configured (which would typically occur in another Registry, if it needs to happen), then rather than falling back to the default instance (which is what I would expect) a call like this [Container].GetAllInstances<ISomeOtherThing>(); results in the following: System.NotSupportedException: Instance's of type 'StructureMap.Pipeline.DefaultInstance' does not support ToNamedClose() and cannot be used as a MissingInstance I'm guessing something is wrong in my registration... but what? A: Based on a conversation with Jeremy Miller in StructureMap's Gitter IM channel, it seems as if this is an oversight in the current implementation, and is likely to be fixed shortly. For anyone else needing it, the bug report can be found at https://github.com/structuremap/structuremap/issues/438
doc_23526884
The problem is that the portrait pictures are displayed as landscape pictures, but zoomed in and clipped in half. Landscape pictures are also clipped to some extent, depending on window size. How do I get colorbox to automatically scale all images so that the entire image fits nicely inside the window, disregarding the orientation or size? See the illustration below for a demonstration of the problem. A: Found a solution (though not optimal) thanks to Vitalii Masilianok tip about max-height In the colorbox css I set: #cboxContent img { max-height: 100%; } And then I have to use the onComplete callback to resize the Colorbox: $(".gallery").colorbox({ maxWidth: "95%", maxHeight: "95%", transition: "none", onComplete: function() { $.colorbox.resize({ width: $('.cboxPhoto').width() }) } }); Using this solution I remove the transition, otherwise I get awkward sizeup-sizedown transitions between each slide. A: Try this attitude: * *Compute the widthRatio as imageWidth / winWidth, heightRatio as imageHeight / winHeight *Compute the ratio as Math.max(widthRatio, heightRatio) *Set the image size to original imageWidth / ratio and original imageHeight / ratio *Hook the function on window.load and window.resize See this code var image = document.getElementById("image"); var origWidth = image.offsetWidth, origHeight = image.offsetHeight; function setImageSize() { var winWidth = window.innerWidth, winHeight = window.innerHeight; var ratioWidth = origWidth / winWidth, ratioHeight = origHeight / winHeight; var ratio = Math.max(ratioWidth, ratioHeight); // var ratio = Math.max(ratio,1); uncomment this not to enlarge small images with(image.style) { width = origWidth / ratio - 20 + "px"; // 10 px margin height = origHeight / ratio - 10 + "px"; } } window.addEventListener("load",setImageSize); window.addEventListener("resize",setImageSize); in this fiddle
doc_23526885
A: If the machines are suspended or idle you could create a windows service with a System.Timer: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace WindowsService1 { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } private System.Timers.Timer m_mainTimer; private bool m_timerTaskSuccess; protected override void OnStart(string[] args) { try { // // Create and start a timer. // m_mainTimer = new System.Timers.Timer(); m_mainTimer.Interval = 60000; // every one min m_mainTimer.Elapsed += m_mainTimer_Elapsed; m_mainTimer.AutoReset = false; // makes it fire only once m_mainTimer.Start(); // Start m_timerTaskSuccess = false; } catch (Exception ex) { // omitted } } protected override void OnStop() { try { // Service stopped. Also stop the timer. m_mainTimer.Stop(); m_mainTimer.Dispose(); m_mainTimer = null; } catch (Exception ex) { // omitted } } void m_mainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { // do some work m_timerTaskSuccess = true; } catch (Exception ex) { m_timerTaskSuccess = false; } finally { if (m_timerTaskSuccess) { m_mainTimer.Start(); } } } } }
doc_23526886
Registering UDF in spark spark.udf.registerJavaFunction("getGeneratedRand","com.test.RandNumGenerator",StringType()) UDF Code for Random num generation import java.util.Calendar; import java.util.Random; import org.apache.spark.api.java.*; import org.apache.spark.SparkConf; import org.apache.spark.sql.*; import org.apache.spark.sql.api.java.UDF0; import org.apache.spark.sql.api.java.UDF1; import org.apache.spark.sql.types.DataTypes; import org.apache.commons.lang3.RandomStringUtils; public class RandNumGenerator implements UDF0<String> { static char[] characters; static Long randomSeed = null; static Random random = null; private Random getRandom() { if (random == null) { synchronized (RandNumGenerator.class) { if (random == null) { randomSeed = System.currentTimeMillis(); random = new Random(randomSeed); } } } return random; } @Override public String call() throws Exception { { if(characters==null){ characters = new char[] {'1','2','3','4','5','6','7','8','9'}; } String generatedRandom=""; generatedRandom = RandomStringUtils.random(12, 0, 0, false, true, characters, getRandom()); Calendar cal = Calendar.getInstance(); String second = Integer.toString(cal.get(cal.SECOND)); if(second.length()<2){ second = "0"+second; } String millisecond = Integer.toString(cal.get(cal.MILLISECOND)); if(millisecond.length()==1){ millisecond = "00"+millisecond; }else if(millisecond.length()==2){ millisecond = "0"+millisecond; } generatedRandom = "NEW_" + generatedRandom + second + millisecond ; return generatedRandom; } } public static void main(String[] args) throws Exception { characters = new char[] {'1','2','3','4','5','6','7','8','9'}; RandNumGenerator obj = new RandNumGenerator(); obj.call(); String res = obj.call(); System.out.print(res); } } Calling UDF in spark UDF spark.sql("select getGeneratedRand(),getGeneratedRand() from db.test_tbl").show(20,False) Result: +---------------------------------+---------------------------------+ |UDF:getGeneratedRand() |UDF:getGeneratedRand()| +---------------------------------+---------------------------------+ |NEW_26481847455148826 |NEW_26481847455148826 | |NEW_26481847455148826 |NEW_26481847455148826 | |NEW_26481847455148826 |NEW_26481847455148826 | |NEW_26481847455148826 |NEW_26481847455148826 | |NEW_26481847455148826 |NEW_26481847455148826 | |NEW_26481847455148826 |NEW_26481847455148826 | |NEW_26481847455148826 |NEW_26481847455148826 |
doc_23526887
You must register your channel definitions before Flex starts up. So if registering it from a plugin won't work, where should I register it from? Where do I put this code? const myChannel = Flex.DefaultTaskChannels.createChatTaskChannel("myChannel", task => { task.attributes.myAttribute = "test" } ); Flex.TaskChannels.register(myChannel); A: I believe that what you are doing there is registering the TaskChannel in the Flex UI. However, you also need to create the TaskChannel definition in the "back-end" (TaskRouter). This documentation on creating a TaskChannel via the TaskRouter API should be helpful: https://www.twilio.com/docs/taskrouter/api/task-channel#create-a-taskchannel
doc_23526888
all cells textView's text is needed to convert form text to speech(TTS) on click UIButton. The UIButton is in UITableViewCell. Now all cell's textview's text is not being converted from text to speech on button's click. Just one textView's text is converted on button's click UITableViewCell class HomeTableViewCell: UITableViewCell { var homeViewCon: HomeTableViewController? let synth = AVSpeechSynthesizer() @IBAction func ttsBtnClick(_ sender: Any) { guard let ttsBtnCheck = sender as? UIButton else { return } if ttsBtnCheck.isSelected { ttsBtn.setImage(UIImage(named: "tts"), for: .normal) ttsBtnCheck.isSelected = false synth.stopSpeaking(at: AVSpeechBoundary.immediate) } else{ print("ttsBtnClick false ") ttsBtn.setImage(UIImage(named: "ttsBlue"), for: .selected) ttsBtnCheck.isSelected = true textToSpeech() let point = (sender as AnyObject).convert(CGPoint.zero, to: self.homeViewCon?.homeTableView) let indexPath = self.homeViewCon?.homeTableView.indexPathForRow(at: point)! let indexPathRow = indexPath?.row ?? 0 let indexPathSection = self.homeViewCon?.homeTableView.numberOfRows(inSection: (indexPath?.section)!) if indexPathRow < indexPathSection! { let newIndexPath = NSIndexPath(row:(indexPath?.row)! + 1, section:(indexPath?.section)!) self.homeViewCon?.homeTableView.scrollToRow( at: newIndexPath as IndexPath, at:.bottom, animated: true) } } } func textToSpeech(){ let name: String = newsTextView.text let endIndex = name.index(name.endIndex, offsetBy: -3) let truncated = name.substring(to: endIndex) let index2 = truncated.range(of: ".", options: .backwards)?.lowerBound var substring3 = index2.map(truncated.substring(to:)) let utterance = AVSpeechUtterance(string: titleLabel.text!+". "+substring3!) utterance.voice = AVSpeechSynthesisVoice(language: "en-US") synth.speak(utterance) } } A: Please find working solution along with storyboard UI. Swift 4 // // TableViewVC.swift // // Created by Test User on 06/02/18. // Copyright © 2018. All rights reserved. // import UIKit import AVFoundation class customCell: UITableViewCell { @IBOutlet weak var lblTTS: UILabel! @IBOutlet weak var btnTTS: UIButton! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } class TableViewVC: UIViewController { @IBOutlet weak var tblTTS: UITableView! var arrTTS = [ "This is first text", "This is second text", "This is third text", "This is fourth text", "This is fifth text", "This is sixth text", "This is seventh text", "This is eighth text", "This is ninth text", "This is tenth text", "This is eleventh text", "This is twelfth text", ] let speechSynthesizer = AVSpeechSynthesizer() var previousSelectedIndexPath : IndexPath? override func viewDidLoad() { super.viewDidLoad() speechSynthesizer.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func btnTTSClicked(sender: UIButton) { let point = sender.convert(CGPoint.zero, to: self.tblTTS) let indexPath = self.tblTTS.indexPathForRow(at: point) if previousSelectedIndexPath == indexPath { let cell = self.tblTTS.cellForRow(at: indexPath!) as! customCell speechSynthesizer.stopSpeaking(at: .immediate) cell.btnTTS.setTitle("TTS", for: .normal) previousSelectedIndexPath = nil } else { if previousSelectedIndexPath == nil { previousSelectedIndexPath = indexPath let cell = self.tblTTS.cellForRow(at: indexPath!) as! customCell cell.btnTTS.setTitle("Speaking", for: .normal) if speechSynthesizer.isSpeaking { speechSynthesizer.stopSpeaking(at: .immediate) } else { let speechUtterance = AVSpeechUtterance(string: self.arrTTS[indexPath!.row]) DispatchQueue.main.async { self.speechSynthesizer.speak(speechUtterance) } } } else { let oldCell = self.tblTTS.cellForRow(at: previousSelectedIndexPath!) as! customCell oldCell.btnTTS.setTitle("TTS", for: .normal) let cell = self.tblTTS.cellForRow(at: indexPath!) as! customCell cell.btnTTS.setTitle("Speaking", for: .normal) previousSelectedIndexPath = indexPath if speechSynthesizer.isSpeaking { speechSynthesizer.stopSpeaking(at: .immediate) } else { let speechUtterance = AVSpeechUtterance(string: self.arrTTS[indexPath!.row]) DispatchQueue.main.async { self.speechSynthesizer.speak(speechUtterance) } } } } } } extension TableViewVC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrTTS.count } //---------------------------------------------------------------- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell cell.lblTTS.text = self.arrTTS[indexPath.row] cell.btnTTS.addTarget(self, action: #selector(btnTTSClicked(sender:)), for: .touchUpInside) return cell } //---------------------------------------------------------------- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } } extension TableViewVC: AVSpeechSynthesizerDelegate { func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { speechSynthesizer.stopSpeaking(at: .word) if previousSelectedIndexPath != nil { let speechUtterance = AVSpeechUtterance(string: self.arrTTS[previousSelectedIndexPath!.row]) DispatchQueue.main.async { self.speechSynthesizer.speak(speechUtterance) } } } } A: The problem is that not all cells are visible during you click the button on one of them so while user enters text in the textView and scroll the text is lost so , so implement didEndDisplaying to store the current textView's text in the a global array and when cell button clicked loop through the array contents and do tts for every text optional func tableView(_ tableView: UITableView,didEndDisplaying cell: UITableViewCell,forRowAt indexPath: IndexPath)
doc_23526889
A: SMS actually uses the same API as other messages (like email). The key difference is that you want to pick the SMS account specifically, and you probably want to build is as part of a conversation. Using the Message part of the BlackBerry PIM API, try something like this: MessageService messageService; AccountService accountService; //Get the SMS/MMS account QList<Account> accountList = accountService.accounts(Service::Messages,"sms-mms"); AccountKey accountId = accountList.first().id(); // Create a contact to whom you want to send sms/mms. Put the right phone number in yourself int contactKey = -1; MessageContact recipient = MessageContact(contactKey, MessageContact::To,"5555555555", "5555555555"); //Create a conversation because sms/mms chats most of the time is a conversation ConversationBuilder* conversationBuilder = ConversationBuilder::create(); conversationBuilder->accountId(accountId); QList<MessageContact> participants; participants.append(recipient); conversationBuilder->participants(participants); Conversation conversation = *conversationBuilder; ConversationKey conversationId = messageService.save(accountId, conversation); //Create a message Builder for sms/mms MessageBuilder* messageBuilder = MessageBuilder::create(accountId); messageBuilder->addRecipient(recipient); // SMS API's handle body as an attachment. QString body = "body of the sms"; messageBuilder->addAttachment(Attachment("text/plain","body.txt",body)); messageBuilder->conversationId(conversationId); Message message; message = *messageBuilder; //Sending SMS/MMS MessageKey key = messageService.send(accountId, message); qDebug() << "+++++++ Message sent" << endl;`
doc_23526890
Table 1: StationStatus Table 2: DetectorStatus I can excecute a query as followed: SELECT TOP 1000 [DetectorStatusID], [DetectorID], [DateTime], [DetectorModeID], NULL as StationModeID, [Status] FROM [GMS_MAN].[dbo].[DetectorStatus] UNION SELECT TOP 1000 [StationStatusID], [DetectorID], [DateTime], NULL as DetectorMOdeID, [StationModeID], [Status] FROM [GMS_MAN].[dbo].StationStatus ORDER BY Status Which will result in the 2 tables combined in 1. However, I don't know how to do this in the code. The query I'm currently executing is only for the DetectorStatus Table [Query] [OutputCache(OutputCacheLocation.Server, 60)] public IQueryable<DetectorStatu> GetDatabacklog(int userID) { User user = ObjectContext.Users .Include("TeamMemberships") .First(u => u.UserID == userID); var teamIDs = user.TeamMemberships.Select(t => t.TeamID).ToList(); var siteIDs = ObjectContext.SiteMemberships.Where(t => teamIDs.Contains(t.TeamID)).Select(t => t.SiteID).ToList(); var DetectorStatus = ObjectContext.DetectorStatus .Include("Detector") .Include("Detector.Track") .Include("Detector.Site") .Include("Detector.EnabledDetectorTypes") .Include("Detector.EnabledDetectorTypes.DetectorType") .Where(d => siteIDs.Contains(d.Detector.SiteID)) .OrderBy(d => d.Status); return DetectorStatus; } And I call it like: private void GetDatabacklog() { LoadOperation<DetectorStatu> loadOp = context.Load(context.GetDatabacklogQuery(App.CurrentUser.UserID), LoadBehavior.RefreshCurrent, LoadDatabacklogCompleted, null); } private void LoadDatabacklogCompleted(LoadOperation<DetectorStatu> loadOperation) { //The rest of the code where i show the results. } My question, how can I use this in multiple tables? Because in the query I need to call StationStatu and DetectorStatu, however I don't know how to do this. When I add .Union to anything, I get the following error: The code I'm using: var detectorSt = ObjectContext.DetectorStatus.Select(x => new { x.DetectorID, x.Status}); var stationSt = ObjectContext.StationStatus.Select(x => new { x.DetectorID, x.Status}); var unioned = detectorSt.Union(stationSt); return unioned; A: I can't see any reason to query the data from two tables in a single query, without linking the results in any way. So I suggest you query the tables separately, select them into a common data object and merge them in client rather than server side (you can still sort the queries on server if you want, then just merge sorted data in client). public class StatusTransferObject { public int DetectorId { get; set; } public DateTimeOffset DateTime { get; set; } public int? DetectorModeId { get; set; } public int? StationModeId { get; set; } public decimal Status { get; set; } } var orderedObjects1 = ObjectContext.DetectorStatus.OrderBy(s => s.Status).Select(s => new StatusTransferObject { DetectorId = s.DetectorID, DateTime = s.DateTime, DetectorModeId = s.DetectorModeID, StationModeId = null, Status = s.Status }); var orderedObjects2 = ObjectContext.StationStatus.OrderBy(s => s.Status).Select(s => new StatusTransferObject { DetectorId = s.DetectorID, DateTime = s.DateTime, DetectorModeId = null, StationModeId = s.StationModeID, Status = s.Status }); var mergedObjects = MergeSorted(orderedObjects1, orderedObjects2, (x1, x2) => x1.Status.CompareTo(x2.Status)).ToList(); MergeSorted is taken from the following question: Is there an easy way to merge two ordered sequences using LINQ?
doc_23526891
I have an instance of MyType1, arg, passed in as an argument to a method. If arg is an instance of MyType2, then I'd like to perform some logic, transforming the instance. My code looks something like the code below. Having to create a new local variable b feels inelegant - is there a way of achieving the same behavior without the additional local variable? public MyType1 MyMethod(MyType1 arg) { if(arg is MyType2) { MyType2 b = arg as MyType2; //use b (which modifies "arg" as "b" is a reference to it)... } return arg; } A: Note that the "is" and "as" is duplicating the test; either use is and then (once you know) just cast - or use as in the first place and test for null. Re your issue; if you only want to do one thing - then cast: if(arg is MyType2) { ((MyType2)arg).SomeSpecialMethod(); } Otherwise - perhaps a virtual method (on the base-type), or just refactor the logic out into another method, so you have: if(arg is MyType2) { StuffThatTakesType2((MyType2)arg); } But persoanlly, I'd just use the extra variable: MyType2 whatever = arg as MyType2; if(whatever != null) { whatever.Foo = 123; whatever.Bar(); } A: No; you need to create a separate variable. Also, your code performs more casts than necessary; it would be a little bit faster like this: MyType2 b = arg as MyType2; if(b != null) { //Use b } A: I would say option 1 is to put all the modifying code (your comment line) as a function of MyType2, and then do (arg as MyType2).Foo() on it. Option 2 is to implement MyMethod on both MyType1 and as an override in MyType2, and just call it without worrying. The MyType1 implementation may do nothing, which isn't the best design. edit: technically not a violation of LSP since that only applies in the reverse of this situation (MyType2 shouldn't break behavior of MyType1).
doc_23526892
[0]; Could not resolve type id 'console' into a subtype of [simple type, class io.dropwizard.logging.AppenderFactory]: known type ids = [AppenderFactory] Here is the snippet of my .yml file: logging: appenders: - type: console timeZone: UTC logFormat: '%-5level [%date{ISO8601}] [%X{requestId}] %c: %msg%n%rootException' I was able to find posts about similar issues. For instance, this thread here suggests to check if file META-INF/services/io.dropwizard.logging.AppenderFactory is in the application jar and if it contents is as following: io.dropwizard.logging.ConsoleAppenderFactory io.dropwizard.logging.FileAppenderFactory io.dropwizard.logging.SyslogAppenderFactory I have verified it. In my case file is where it supposed to be and it has exactly the same contents. Any help will be greatly appreciated. Dropwizard version 0.9.2 A: Does the Gradle produce a Uber/Fat Jar (A jar with all it's dependencies inside itself) or a simple jar with only your Dropwizard app? It's advisable to build an Fat-jar for Dropwizard deployments, so do switch over to this style if you're not doing so. Now while building a Fat-Jar, you need to do the following to solve your problem (this was mentioned in the discussion you linked) If you use maven-shade plugin for building a fat jar, don't forget about SPI resource transformer for collecting SPI resources into the jar. <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> To do the same in Gradle, check this discussion. HTH.
doc_23526893
I'm working with code that attempts to sort by that value but unfortunately, since it's a string, I get the unsurprising behavior that "10" comes before "2". I do not have license to change the data in the table, so I'm looking for a way to write the order so that it orders by the value as an integer rather than as the string it naturally is. Here is some toy SQL to hopefully better show what I'm asking: INSERT INTO hstore_test (sale) VALUES ('"milk"=>"4", "bread"=>"2", "bananas"=>"12", "cereal"=>"1"'); Now at this point I want to get all the things, sorted by milk -> value: SELECT * FROM hstore_test ORDER BY sale -> 'milk'; This unfortunately sorts by the string value of milk ("4" in the example above). I've been kind of envisioning something like SELECT * FROM hstore_test ORDER BY CAST(sale -> 'milk' as INT); but I can't convince myself that's correct.
doc_23526894
In this case in the diagram, I'm relating a TeamMember via TeamMemberGUID in a many to many setup via the ObjectTag junction table a 'la the ObjectGUID field. I could just as easily relate any other GUID keyed entity in the same way. Thus I have a central repo of tags that can "tag" various entities. Pretty slick, or so I thought. The trouble is I can't seem to find a way to bring this data back with LINQ to Entities. I'm using EF Code First and I want to bring this back in one query if possible. The closest I've gotten is using ugly outer join syntax: var team = from tm in db.TeamMembers join ot in db.ObjectTags on tm.TeamMemberGuid equals ot.ObjectGuid into objTags // outer join to ObjectTag from ot2 in objTags.DefaultIfEmpty() join tags in db.Tags on ot2.TagId equals tags.TagId into tmTags // join via ObjectTag to Tag select new TeamMemberDTO { TeamMember = tm, Tags = tmTags }; But this gives me a flattened set (4 team members sharing 2 tags can equal up to 8 results) where what I'm looking for is a hierarchical TeamMember object with a Tags property of the associated tags. I've tried normal relation properties but EF doesn't want to map more than one entity to a junction table so that's out. I've also tried a group by but haven't gotten far with that. Is this out for LINQ to EF? Do I need to consider a view or something? Really hoping an EF pro can help me on this one. I feel like I'm missing something or taking the wrong approach.
doc_23526895
CustomerID Itemset 1 1 1 3 1 7 2 6 2 7 3 4 ... ... I want to write this table in Datatable 'Matrix' where the Rows are Itemset={1,2,3,4,5,6....,k} and Columns are CustomerID={1,2,3,4,...,x} and the rows are 1 if the 'Itemset' belongs to the CustomerID. The output I want is like.. 1 2 3 4 5 6 7 ............. x 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 2 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 3 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 4 5 6 /And so on! 7 8 9 ` I tried to code it but the problem is in VS Parameters for SQL Query don't work with Loops. This is my code- objConnection.Open() Dim matrix As DataTable = New DataTable("Retail") intcount = 0 For intcount = 1 To noofCustomerID_col matrix.Columns.Add(intcount, GetType(Integer)) Next Dim i As Integer Dim workRow As DataRow Dim Boolin As Boolean For i = 1 To 9 ObjCommand.CommandText = "Select count(*) from Retail Where CustomerID=@in and Itemset=@in" ObjCommand.Parameters.AddWithValue("@in", i) {{I Get Error here as I can't Loop Parameters}} Boolin = ObjCommand.ExecuteScalar() workRow = matrix.NewRow() workRow(0) = i workRow(1) = Boolin matrix.Rows.Add(workRow) Next Kindly Help. I know this code can completely be wrong and it's okay if you can suggest totally different way of doing it. I've been stuck for quite some time now! Thanks. If any clarification is needed I shall explain as many times needed in the comments. A: Like Tab Alleman suggested, SQL PIVOT can come handy here. Dynamic SQL is also needed. DECLARE @DynamicColumn NVARCHAR(MAX), @DynamicQuery NVARCHAR(MAX) SELECT @DynamicColumn = SELECT '[' + CONVERT(NVARCHAR, CustomerID) + '],' FROM Retail AS Customer ORDER BY CustomerID FOR XML PATH('') SELECT @DynamicColumn = SUBSTRING(@DynamicColumn, 0, DATALENGTH(@DynamicColumn) / 2)--REMOVE EXTRA "," SELECT @DynamicQuery = 'SELECT * FROM ( SELECT CustomerID, ItemSet FROM Retail) AS D PIVOT ( COUNT([CustomerID]) FOR Itemset IN (' + @DynamicQuery + ') ) AS P' EXECUTE(@DynamicQuery)
doc_23526896
I found similar error: https://issues.apache.org/jira/browse/CAMEL-8829 but it should be resolved in version 2.16. Error stacktrace: 2019-04-17 15:13:05,489 | ERROR | ead #241 - Split | ReportError | 151 - org.apache.camel.camel-core - 2.16.5 | java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442) at java.util.HashMap$EntryIterator.next(HashMap.java:1476) at java.util.HashMap$EntryIterator.next(HashMap.java:1474) at java.util.AbstractMap.toString(AbstractMap.java:554) at java.lang.String.valueOf(String.java:2994) at java.lang.StringBuilder.append(StringBuilder.java:131) at java.util.AbstractMap.toString(AbstractMap.java:559) at java.lang.String.valueOf(String.java:2994) at java.lang.StringBuilder.append(StringBuilder.java:131) at org.apache.camel.processor.DefaultExchangeFormatter.format(DefaultExchangeFormatter.java:120) at org.apache.camel.processor.CamelLogProcessor.process(CamelLogProcessor.java:76) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109) at org.apache.camel.processor.CamelLogProcessor.process(CamelLogProcessor.java:71) at org.apache.camel.component.log.LogProducer.process(LogProducer.java:39) at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196) at org.apache.camel.processor.Pipeline.process(Pipeline.java:121) at org.apache.camel.processor.Pipeline.process(Pipeline.java:83) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196) at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62) at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196) at org.apache.camel.processor.Pipeline.process(Pipeline.java:121) at org.apache.camel.processor.Pipeline.process(Pipeline.java:83) at org.apache.camel.processor.ChoiceProcessor.process(ChoiceProcessor.java:117) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109) at org.apache.camel.processor.MulticastProcessor.doProcessParallel(MulticastProcessor.java:823) at org.apache.camel.processor.MulticastProcessor.access$200(MulticastProcessor.java:84) at org.apache.camel.processor.MulticastProcessor$1.call(MulticastProcessor.java:319) at org.apache.camel.processor.MulticastProcessor$1.call(MulticastProcessor.java:304) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Main message broker route - it's delegate operations to other module: <camelContext xmlns="http://camel.apache.org/schema/spring"> <propertyPlaceholder id="properties" location="ref:preProps" /> <threadPool id="mbkPool" threadName="mbkPool" poolSize="20" maxPoolSize="100" keepAliveTime="180" /> <onException> <exception>java.lang.Exception</exception> <log message="Error in MBK. ${property.CamelExceptionCaught} ${exception.message}" loggingLevel="ERROR" logName="log:error" /> <log message="Stacktrace: ${exception.stacktrace}" loggingLevel="ERROR" logName="log:error" /> </onException> <route streamCache="true"> <from uri="cxf:bean:queryServiceEndpoint" /> <convertBodyTo type="a.b.c.Body"/> <process ref="aProcessor" /> <process ref="sendProcessor" /> <log message="Invoking for ${property.invokeSystems}" logName="BeforeInvoke" loggingLevel="DEBUG" /> <to uri="log:BeforeInvoke?level=DEBUG&amp;showAll=true" /> <recipientList ignoreInvalidEndpoints="true" delimiter="," executorServiceRef="mbkPool" parallelProcessing="true"> <exchangeProperty>invokeSystems</exchangeProperty> </recipientList> <process ref="responseQueryProcessor" /> <to uri="log:AfterInvoke?level=DEBUG" /> </route> </camelContext> Module which throws error: <route streamCache="true"> <from uri="vm:invoke?concurrentConsumers={{concurrentConsumers}}" /> <to uri="log:BeginPartialQuery?level=DEBUG" /> <split parallelProcessing="true"> <log message="queryType = OBJECT" loggingLevel="DEBUG" logName="log:ObjectOperation" /> <to uri="direct:processCepSyncOperation" /> </split> </route> <route streamCache="true"> <from uri="direct:processSyncOperation" /> <to uri="log:BeginProcessLevel=DEBUG" /> <setProperty propertyName="operation"> <xpath resultType="java.lang.String">/operation</xpath> </setProperty> <setBody> <simple>${property.bodyHolder}</simple> </setBody> <to uri="log:ProcessSyncOperation?level=DEBUG&amp;showHeaders=true" /> <to uri="xslt:aaaa.xslt" /> <to uri="log:afterXslt?level=DEBUG" /> <to uri="direct:processRequest" /> </route> I found that probably <to uri="log:ProcessSyncOperation?level=DEBUG&amp;showHeaders=true" /> line cause error. Is it possible to workaround this problem? (I know that I can delete this log but maybe there is other options)
doc_23526897
The below an example of code has been written to filter the words among the displayed data from JSON feed URL. angular.module('sample', []). controller('sampleController', ['$scope', '$http', function($scope, $http) { var url = "https://spreadsheets.google.com/feeds/list/153Obe1TdWlIPyveZoNxEw53rdrghHsiWU9l-WgGwCrE/od6/public/values?alt=json"; $http.get(url) .success(function(data, status, headers, config) { $scope.users = data.feed.entry; console.log($scope.users); }) .error(function(error, status, headers, config) { console.log(status); console.log("Error occured"); }); // code to highlight $scope.highlight = () => { //create copy of the original array $scope.filteredContent = JSON.parse(JSON.stringify($scope.users)); $scope.filteredContent.forEach(fc => { const regEx = new RegExp($scope.search); alert("here"); fc.question = fc.gsx$topic.$t.replace(regEx, '<span class="highlight">${$scope.search}</span>'); fc.answer = fc.gsx$response.$t.replace(regEx, '<span class="highlight">${$scope.search}</span>'); }); }; // code to highlight $scope.search=''; $scope.searchFilter=function(item){ if(item.gsx$topic.$t.toLowerCase().indexOf($scope.search.toLowerCase()) != -1 || item.gsx$response.$t.toLowerCase().indexOf($scope.search.toLowerCase()) != -1){ return true; } return false; } }]); <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.min.js"></script> <div ng-app="sample" ng-controller="sampleController"> <div class="black"> <input type="text" name="search" ng-keyup="highlight()" ng-model="search" placeholder="search"/> </div> <br> <br> <br> <table style="border: 1px solid black ;"> <tbody> <tr> <td> <center><b>Question</b></center> </td> <td> <center><b>Response</b></center> </td> </tr> <tr ng-repeat="user in users | filter:searchFilter"> <td style="border: 1px solid black ; width:30%;white-space: pre-wrap;" ng-bind-html="user.gsx$topic.$t">{{user.gsx$topic.$t}}</td> <td style="border: 1px solid black ; width:70%;white-space: pre-wrap;" ng-bind-html="user.gsx$response.$t">{{user.gsx$response.$t}}</td> </tr> </tbody> </table> </div> Code link: https://jsfiddle.net/bjqsgfzc/1/ A: You'll need to use the $sce service Strict Contextual Escaping. Add this service in your controller declaration, like this: controller('sampleController', ['$scope', '$http', '$sce', function($scope, $http, $sce) { Now you must define a function that will only inject a span tag with a CSS class name with the yellow color to highlight, when the searched text is found, through the $sce.trustAsHtml method, to indicate AngularJS, the injected is safe content. $scope.highlightText = function(text, search) { if (search && search.length === 0) { // Returns the default content. return $sce.trustAsHtml(text); } // Define a regular expression to find the text globally and ignoring capital letters. var regex = new RegExp(search, 'gi'); // If you already found the text then inject a span element with CSS class to highlight that you found. return $sce.trustAsHtml(text.replace(regex, '<span class="foundText">$&</span>')); }; In the previous regular expression replacement text, $& indicates to display the captured text that matches the regular expression within the replaced. In the HTML, within the ng-repeat, add the ngBindHtml directive with highlightText function where the first parameter is the text that you'll have to search and the second parameter is the text to find. In your case, in this way: <tr ng-repeat="user in users | filter:searchFilter"> <td style="border: 1px solid black ; width:30%;white-space: pre-wrap;" ng-bind-html="highlightText(user.gsx$topic.$t, search)">{{user.gsx$topic.$t}}</td> See in this example: angular.module('sample', []). controller('sampleController', ['$scope', '$http', '$sce', function($scope, $http, $sce) { var url = "https://spreadsheets.google.com/feeds/list/153Obe1TdWlIPyveZoNxEw53rdrghHsiWU9l-WgGwCrE/od6/public/values?alt=json"; $http.get(url) .success(function(data, status, headers, config) { $scope.users = data.feed.entry; console.log($scope.users); }) .error(function(error, status, headers, config) { console.log(status); console.log("Error occured"); }); $scope.search = ''; $scope.searchFilter = function(item) { if (item.gsx$topic.$t.indexOf($scope.search) != -1 || item.gsx$response.$t.indexOf($scope.search) != -1) { return true; } return false; }; $scope.highlightText = function(text, search) { if (search && search.length === 0) { // Returns the default content. return $sce.trustAsHtml(text); } // Define a regular expression to find the text globally and ignoring capital letters. var regex = new RegExp(search, 'gi'); // If you already found the text then inject a span element with CSS class to highlight that you found. return $sce.trustAsHtml(text.replace(regex, '<span class="foundText">$&</span>')); }; }]); .foundText { background-color: #ff0; color: #f00; } <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.min.js"></script> <div ng-app="sample" ng-controller="sampleController"> <div class="black"> <input type="text" name="search" ng-model="search" placeholder="search" ng-click="didSelectLanguage()" /> </div> <br> <br> <br> <table style="border: 1px solid black ;"> <tbody> <tr> <td> <center><b>Question</b></center> </td> <td> <center><b>Response</b></center> </td> </tr> <tr ng-repeat="user in users | filter:searchFilter"> <td style="border: 1px solid black ; width:30%;white-space: pre-wrap;" ng-bind-html="highlightText(user.gsx$topic.$t, search)">{{user.gsx$topic.$t}}</td> <td style="border: 1px solid black ; width:70%;white-space: pre-wrap;" ng-bind-html="highlightText(user.gsx$response.$t, search)">{{user.gsx$response.$t}}</td> </tr> </tbody> </table> </div> Hope this helps! A: You can add <span> with highlighted class. Make sure to create a deep copy of the original array. I used JSON.parse(JSON.stringify(...)). In addition, since we are adding the <span> and want to display it as html, we need to use ng-bind-html. In order to do that, we need to add ngSanitize as module dependency. angular.module('myApp', ['ngSanitize']) .controller('myController', ['$scope', ($scope) => { const content = [{ question: 'Question 1', answer: 'Answer 1' }, { question: 'Question 2', answer: 'Answer 2' } ]; //create copy of the original array $scope.filteredContent = JSON.parse(JSON.stringify(content)); $scope.highlight = () => { //create copy of the original array $scope.filteredContent = JSON.parse(JSON.stringify(content)); $scope.filteredContent.forEach(fc => { const regEx = new RegExp($scope.searchText); fc.question = fc.question.replace(regEx, `<span class="highlight">${$scope.searchText}</span>`); fc.answer = fc.answer.replace(regEx, `<span class="highlight">${$scope.searchText}</span>`); }); }; }]); table { border-collapse: collapse; margin-top: 10px; border: 1pt solid black; width: 100%; } td { border: 1pt solid black; margin: 0; padding: 0; } .highlight { background-color: yellow; } <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.7.9/angular-sanitize.js"></script> <div ng-app="myApp" ng-controller="myController"> <input type="text" ng-model="searchText" ng-keyup="highlight()" placeholder="Search"> <table> <tr ng-repeat="c in filteredContent"> <td ng-bind-html="c.question"> </td> <td ng-bind-html="c.answer"> </td> </tr> </table> </div>
doc_23526898
import matplotlib.pyplot as plt import collections as col import numpy as np class Graph(object): """Single 2-D dynamic plot. The axes must be same length and have both minimum and maximum possible values. """ def __init__(self, window, subplot_num, x_axis, y_axis): ax = window.add_subplot(subplot_num) self.y, = ax.plot(x_axis, # Obtain handle to y axis. y_axis, marker='^' ) self.y_data = col.deque(y_axis, # Circular buffer. maxlen=len(y_axis) ) # Make plot prettier plt.grid(True) plt.tight_layout() def add_datapoint(self, y): self.y_data.appendleft(y) # Remember - circular buffer. self.y.set_ydata(self.y_data) I am passing to x_axis range(60) to set the static horizontal axis. y_axis is getting range(10, 60) in order to set it's range. From then on, I listen to stdin and add a new point each second. The problem is, that the inital graph is hidious: I want to remove the initial diagonal line. I tried initializing y_axis with NaNs and calling ax.set_yrange(), but that doesn't do what I am opting for. I also tried not passing y values, but mpl.plot wants x and y axes of equal length. How can I remove the initial diagonal line? I am ok both with manually setting y range or the graph resizing dynamically as new data arrives.
doc_23526899
My show.blade.php @section('content') <p>This is user {{ $profile->name }}</p> <p>This is address {{ $profile->address }}</p> <img src= "/storage/images/{{ $profile->images }}" style="width:504px;height:228px /> @endsection this works fine. now edit.blade.php <div class="container"> <form method="POST" action="/profiles/{{$profile->id}}" enctype="multipart/form-data"> {{ method_field('PATCH') }} {{ csrf_field() }} <div class="form-group"> name <input type="text" name="name" value="{{ $profile->name }}" /> </div> <div class="form-group"> address <input type="textarea" name="address" value="{{ $profile->address }}" /> </div> <div class="form-group"> @if ("/storage/images/{{ $profile->images }}") <img src="{{ $profile->image }}"> @else <p>No image found</p> @endif image <input type="file" name="image" value="{{ $profile->images }}"/> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div>`` </div> when I try to save the form a diffrent images path is saved in database table when updating the images ie /tmp/phpHs0Io6 store controller is public function store(Request $request) { $this->validate($request, [ 'name' => 'required|max:255', 'address' => 'nullable' , ]); $profile = new profile; $profile-> user_id = auth()->id(); $profile-> name = $request->name; $profile-> address = $request->address; $request->image->store('public/images'); $path = $request->image->hashName(); $profile-> images = $path; $profile->save(); return redirect('/home'); } and update controller is public function update(Request $request, profile $profile) { $this->validate($request, [ 'name' => 'required|max:255', 'address' => 'nullable' , ]); $profile->update($request->all()); $profile-> name = $request->name; $profile-> address = $request->address; $request->image->store('public/images'); $path = $request->image->hashName(); $profile-> images = $path; $profile->save(); return redirect('/home'); } A: First of all before you save an image you have to check if user uploaded one; Your way of saving image is wrong use this pattern; public function update(Request $request, profile $profile) { $this->validate($request, [ 'name' => 'required|max:255', 'address' => 'nullable' , ]); $profile->update($request->all()); $profile-> name = $request->name; $profile-> address = $request->address; if(Input::hasFile('image')){ $file = Input::file('image'); $destinationPath = public_path(). '/uploads/'; $filename = $file->getClientOriginalName(); $file->move($destinationPath, $filename); //then proceeded to save user $profile-> images = $destinationPath.$filename; $profile->save(); return redirect('/home'); }else{ $profile->save(); return redirect('/home'); } } same on update function. A: Instead of directly writing path in if condition, use file_exists function to check whether your image exist at the given location. For more info check this link A: i am a bit late but i have a suggestion: so if ur image is being uploaded in storage this code might work, u still need to resize image so its not over the whole site: <div class="pull-right"> <label for="image">Choosen Datei:</label> <img src="{{Storage::disk('local')->url($profile->image)}}" alt=""> <label for="image" >Choose data</label > <input type="file" name="image" id="image" class="form-control" /> </div>