Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from 2018-02-21T10:21:19Z
Updated: 4 hours 19 min ago

Fold with closure that returns a Result

Wed, 11/15/2017 - 21:39

I'm using the regex crate to find some text with this regex:

lazy_static! { static ref FIND_STEPS_RE: Regex = Regex::new(r"my regex").unwrap(); }

I want to find all possible captures and iterate over them:


Each captured element consists of 2 values: an operation and a number. For example, the output could be:

[("+", "10"), ("-", "20"), ("*", "2")]

I want to iterate over it, parse the numbers and apply the operation.

I tried:

let e = FIND_STEPS_RE.captures_iter(script_slice) .fold(0, |sum, value| apply_decoding_step)?;

where apply_decoding_step is:

fn apply_decoding_step(sum: i32, capture: regex::Captures<>) -> Result<i32> { let number = parse_number(&capture[2])?; match &capture[1] { "+" => Ok(sum + number), "-" => Ok(sum - number), "*" => Ok(sum * number), "/" => Ok(sum / number), _ => bail!("Unknown step operator"), } }

But I got this error:

error[E0271]: type mismatch resolving `<fn(i32, regex::Captures<'_>) -> std::result::Result<i32, Error> {apply_decoding_step} as std::ops::FnOnce<(i32, regex::Captures<'_>)>>::Output == i32` --> src/ | 122 | .fold(seed, apply_decoding_step); | ^^^^ expected enum `std::result::Result`, found i32 | = note: expected type `std::result::Result<i32, Error>` found type `i32`

I assume this is because I'm trying to fold a Result into a i32, but since I need to parse the second capture value and also need that otherwise case in my match, how can I fix that?

Atom for a list in Erlang

Wed, 11/15/2017 - 21:04

Can I create a list with atoms as reference for them to later use it in my move method?

createLists(X) -> List = [ listA = lists:seq(1, X), listB = [], listC = [] ], List.

Then I create like T = hello:createLists(10).

move(List, A, B) -> ...

How can I obtain A and B using atoms? I'm pretty new to Erlang so the answer might be obvious.

move is supposed to move top element of the from A to B but I struggle to pass A and B when I do like hello:move(List, ?, ?).

convert each words into one list dataframe

Wed, 11/15/2017 - 20:38

I have a dataframe df:

Suppose a,b,c,d,e,f,g,h,j is a word ,not a single letter.

cate word apple [['a','b'],['c','d','e']] pen [['f','g','h'],['j']]

I want to get one list in word column.So the expected output should be word_list =[u'a b c d e',u'f g h j']

However,when I use the following code:

word_list =[] for line in df['word']: for word in line: word_list.append(word)

So the output is not what I expected.

Find duplicates in two columns in a table

Wed, 11/15/2017 - 19:42

I just browse this post and tried all the scripts but still i am not getting what i am expecting.

Here is my table

Name email BRIAN MAT BRIAN.MAT@abc.Com BRIAN MAT BRIAN MAT@abc.Com AMY Lee AMY.Lee@abc.Com AMY.Lee AMY.Lee@abc.Com Madison Taylor SELECT Name FROM Employee GROUP BY Name HAVING ( COUNT(Name > 1 )



SELECT email FROM Employee GROUP BY email HAVING ( COUNT(email> 1 )



I was trying to group this two script but it shows blank

SELECT Name, email,COUNT(*) FROM Employee GROUP BY Name, email HAVING COUNT(*) > 1

Please correct me what i am missing in my script to acheive the result like below

Name email BRIAN MAT BRIAN.MAT@abc.Com BRIAN MAT BRIAN MAT@abc.Com AMY Lee AMY.Lee@abc.Com AMY.Lee AMY.Lee@abc.Com

Choosing and setting a java class programmatically in the MainActivity

Wed, 11/15/2017 - 18:31

I am building an app that contains a listview. What I am trying to accomplish is when I click on each unique item in the listview, each item will set a particular Java class. I put all of the Java Classes that I want to be able to select inside of a Java package. To give some context, each Java class sets a certain xml file. The reason why I can't just set the xml file is because it requires java to function as well. One of the things that needs to be taken into consideration is that there are multiple Java classes which will need to be disregarded, except for my adapter class, the main activity, and the additional java class that is selected.

Here is the MainActivity. I am using if statements: if (item_position==1) {then set a particular java class}. if (item_position==2) {then set another java class}. The problem is that I am unable to figure out and find out what to put inside the brackets to set the Java class.

public class MainActivity extends AppCompatActivity { ArrayList<String> selectedItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); selectedItems = new ArrayList<String>(); ListView chl = (ListView) findViewById(; chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); String[] items = {"Apple", "Pear", "Banana", "Melon", "Grape", "Blueberry"}; Adapter adapter=new Adapter(this,items); chl.setAdapter(adapter); chl.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { int item_position=i; if (item_position==1){ ////set a particular Java class } if (item_position==2){ ///set another particular java class } Toast.makeText(MainActivity.this, "Item position "+item_position+" clicked", Toast.LENGTH_SHORT).show();

Here is an example of one of the Java classes that I am trying to select. I am also open to setting the xml class by which item I selcted in one of the Java classes instead of the MainActivity.

@Override public View onCreateInputView() { kv = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null); keyboard = new Keyboard(this, R.xml.qwerty); kv.setKeyboard(keyboard); kv.setOnKeyboardActionListener(this); return kv; } private void playClick(int keyCode) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); switch (keyCode) { case 32: am.playSoundEffect(AudioManager.FX_KEYPRESS_SPACEBAR); break; case Keyboard.KEYCODE_DONE: case 10: am.playSoundEffect(AudioManager.FX_KEYPRESS_RETURN); break; case Keyboard.KEYCODE_DELETE: am.playSoundEffect(AudioManager.FX_KEYPRESS_DELETE); break; default: am.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD); } } @Override public void onPress(int primaryCode) { } @Override public void onRelease(int primaryCode) { } @Override public void onKey(int primaryCode, int[] keyCodes) { InputConnection ic = getCurrentInputConnection(); playClick(primaryCode); switch (primaryCode) { case Keyboard.KEYCODE_DELETE: ic.deleteSurroundingText(1, 0); break; case Keyboard.KEYCODE_SHIFT: caps = !caps; keyboard.setShifted(caps); kv.invalidateAllKeys(); break; case Keyboard.KEYCODE_DONE: ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); break; default: char code = (char) primaryCode; if (Character.isLetter(code) && caps) { code = Character.toUpperCase(code); } ic.commitText(String.valueOf(code), 1); } } @Override public void onText(CharSequence text) { } @Override public void swipeLeft() { } @Override public void swipeRight() { } @Override public void swipeDown() { } @Override public void swipeUp() { }

In C, how to use loops to print specific star pattern? [on hold]

Wed, 11/15/2017 - 18:15

I'm attempting to print a pyramid that looks like:

1 * 2 3 ** *** 4 5 6 **** ***** ******

Thus far, I've been able to create the pyramid using arrays for the stars. My code prints:

1 * 2 3 ** *** 4 5 6 **** ***** ******

I'd like to make it as close to the picture as possible - with at least the 1 and 5 lining up.

My code:

int row, count, star, count2 = 0, number = 1, wid = 26; char astArray[6][7] = { "*", "**", "***", "****", "*****", "******" }; for(row = 1; row <= 3; row++){ for(count = 1; count <= row; ++count) { if (row == 1){ printf("%*d", wid, number); ++number; } else if(row == 2){ printf("%*d", (wid - 9), number); ++number; } else{ printf("%*d", (wid - 13), number); ++number; } } printf("\n"); for (star = 0; star <= row - 1; ++star){ if (row == 1){ printf("%*s", wid, astArray[count2]); ++count2; } else if(row == 2){ printf("%*s", (wid - 8), astArray[count2]); ++count2; } else{ printf("%*s", (wid - 12), astArray[count2]); ++count2; } } printf("\n\n"); }

It prints it (almost) perfectly as the picture above describes. I, however, must use loops to print the stars instead of using an array. How do I go about doing this?

Add production into development React Webpack config

Wed, 11/15/2017 - 17:39

I have a simplest possible React environment. That is very efficient in development.

var webpack = require('webpack'); const config = { entry: "./index.js", output: { filename: "bundle.js" }, devtool: 'eval', module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'env'] } } ] } }; module.exports = config;

What I want to do is to add a production build so as to run in console script like this: npm run build, which is defined in package.json:

"build": "webpack --config webpack.config.js"

How can I add production plugins and devtool: "cheap-module-source-map" so that they will work only in production and were not included into development. By production plugins I meant these:

new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new webpack.optimize.UglifyJsPlugin()

I failed to use

var debug = process.env.NODE_ENV !== "production";

with devtool: debug ? "cheap-module-source-map" : "eval", and

plugins: debug ? [] : [//production plugins here ]

How can I embed extra column/external URLs in Flask-appbuilder list/detail model view?

Wed, 11/15/2017 - 14:07

Flask-appbuilder's ModelView can display list and detail for a model. Very handy and save many times for CURD operations.

Sometimes the application demands more features with extra column(s) besides CURD operations. For example, in a IoT related Device ModelView, besides CRUD, I want to link to anther realtime gauge web page, or call Web API offered by device server to send command to device.

In other Python framework, like Tornado/Cyclone, I will manually designed a template page (with extra buttons) and (embed extra) javascript code. But I am still not familiar with FAB's structure.

I can make these extra operations as external links to other exposed methods. And add these links to models as data fields. But I think these design is quite ugly. And its URL is too long to display as well.

Any better ideas? Which methods should be overriden?

Android Architecture Components with Data Binnding

Wed, 11/15/2017 - 13:59

In Android Architecture Components docs on the Handling Lifecycle page in Best practices paragraph, written:

Use Data Binding to maintain a clean interface between your views and the UI controller.

Can someone provide me with link to example on how to use this libraries together?

Structuring Database First model classes with MVVM in WPF App

Wed, 11/15/2017 - 13:58

I am following this course on integrating an MVVM architecture with an WPF app, but using code first. For my own app I am using database first, with only a few tables.

This is my project structure, with the 3 layers, Model-View-ViewModel. In the course he creates two model classes, of course using code first in the model project, while the Data Access project handles migrations and the DbContext.

Now, when I use Database First, EF creates all the model classes for me, but the database context is included as well. My edmx is structured like this:

My question is what I need to place in which project? I'm aware that I have my view models in the UI project, which then use a data service to create a new context, but it seems I can do this all in the UI project.

Breaking a tie in round robin scheduling

Wed, 11/15/2017 - 13:24

I am confused with a basic concept of Round Robin CPU process scheduling, where the short term scheduler adds the process to the ready queue.

If there are 3 process P0, P1 and P2 in the system and a context switch occurs for P1 at 5 seconds and at the same time P2 ARRIVES (i.e. at 5th second). In such a case which process will be inserted first in the ready queue, P1 or P2? The overall average waiting time may not differ in both the cases but the individual waiting time of a process will differ.

How to decode BLOB files after downloading from Azure Storage?

Wed, 11/15/2017 - 10:58

I am trying to decode files after downloading via Azure Storage SDK for Java.

Here is my code:

try { CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString); CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); CloudBlobContainer container = blobClient.getContainerReference("mycontainer"); CloudBlobDirectory blobDirectory = container.getDirectoryReference("shi"); for (ListBlobItem blobItem : blobDirectory.listBlobs()) { if (blobItem instanceof CloudBlob) { CloudBlob blob = (CloudBlob) blobItem; FileOutputStream("/Users/shi/Downloads/" + blob.getName())); } } }

This code downloads all the BLOB files from mycontainer but there are encoded. How can I download them but in decoded form.

Sortable js library not working as expected inside iframe in safari

Wed, 11/15/2017 - 10:57

When sortable library is used inside a iframe in safari, the draggable element is not working as expected as in other browsers. Is there any workaround. Open this in safari browser. The element which is dragged is far away from the cursor pointer Demo URL [,js,output][1]

Is it possible to nest a sift appender inside another sift appender with both of them using a different discriminator?

Wed, 11/15/2017 - 10:57

I have a spring boot application with a varying amount of terminals. I have a requirement that says for each terminal there should be a directory where the log files are stored. These separate log files are one for each thread in the terminal. Below is my logback.xml configuration:

<configuration> <appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender"> <discriminator class=""/> <discriminator> <key>terminalName</key> <defaultValue>logs</defaultValue> </discriminator> <sift> <appender class="ch.qos.logback.core.FileAppender"> <file>C:/Users/wkoonings/AppData/Roaming/console/${terminalName}/app-${threadName}.log</file> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{HH:mm:ss:SSS} | %-5level | %logger{20} | %msg%n%rEx</pattern> </layout> </appender> </sift> </appender> <root level="INFO"> <appender-ref ref="SIFT"/> </root> </configuration>

I do get the different directories but the log files inside the directories are all named:


What is the role of TimeDistributed layer in Keras?

Wed, 11/15/2017 - 10:57

I am trying to grasp what TimeDistributed wrapper does in Keras.

I get that TimeDistributed "applies a layer to every temporal slice of an input."

But I did some experiment and got the results that I cannot understand.

In short, in connection to LSTM layer, TimeDistributed and just Dense layer bear same results.

model = Sequential() model.add(LSTM(5, input_shape = (10, 20), return_sequences = True)) model.add(TimeDistributed(Dense(1))) print(model.output_shape) model = Sequential() model.add(LSTM(5, input_shape = (10, 20), return_sequences = True)) model.add((Dense(1))) print(model.output_shape)

For both models, I got output shape of (None, 10, 1).

Can anyone explain the difference between TimeDistributed and Dense layer after an RNN layer?

Batch file - rename folder within folder but do not know folder name

Wed, 11/15/2017 - 10:57

Hi hope someone can advise:

I extract a folder using 7-zip to a folder called xyz

Inside xyz it then holds the name of the folder I extracted but this changes based on each extraction so cannot hard code my batch file, this subfolder (call it abc [The extraction only every contains 1 folder]) then abc contains standard folders I need to copy to another location.

The problem I have is that I need to either rename the abc to a known items so I can set my path variable or I need to be able to access it regardless of its name and then copy sub folders out to where I need them

My attempts to copy the contents of abc or rename (move) folder abc have failed any suggestions appropriated, below is what I have already tried

Attempt to copy folder contents c:\xyz>xcopy c:\xyz*\ c:\newlocation

c:\xyz>xcopy c:\xyz** c:\newlocation

Attempt to rename the abc folder c:\xyz>dir /o-n move "*" c:\xyz\newname

Thanks Andy

I want to add a css file to use only for Firefox browser

Wed, 11/15/2017 - 10:57

I want to Add a css file link on the header when it is the Firefox browser. I want to add fontawesome CDN link when it is firfox browser. My icon code is working on chrome and IE browser it is not working on firfox I don't want to add online link. Is there any code like Ie browser?

Example:- <!--[if IE]> <link rel="stylesheet" type="text/css" href="all-ie-only.css" /> <![endif]-->

Is it possible to use gulp with .NET NON-Core projects in VS 2017?

Wed, 11/15/2017 - 10:57

I'm finding gulp (fully integrated in Visual Studio 2017) to be an extremely useful tool in my .NET-Core projects.
However, it seems not to work for .NET non-core projects.
I'd like to use gulp-integration in VS-2017 in a .NET-Framework (2.0 to 4.0) (not .NET-Core) project.

Is it possible ?
I need to run watch tasks on solution-load, and pre-build tasks.
Also, I need to be able to load the gulp-packages with the integrated VS-version of NPM.

Note: No administrative rights on the dev-machine, and not going to get any either.

Understanding Memory Layouts of an Interpreter (JVM/JS)

Wed, 11/15/2017 - 10:57

I am trying to understand the memory layout of a process at OS level and we are used to this diagram.

Forget the multithreading part of the diagram but now for general purposes, we assume the "code" block shown in the diagram above to be the binary instructions of our program. This assumes that the code has already been compiled to now be available in its binary form. But what about interpreted languages e.g. a bytecode to be executed by the JVM interpreter. While I am choosing the JVM interpreter here, my question is for any interpreted language and how does it fit in the diagram shown above. My understanding is that the Interpreter itself is a program and therefore has to sit in the code block shown in the diagram above and the .class program in case of Java or a .js file in case of Javascript interpreters is the "argument" so to speak that this interpreter works upon to translate them to OS/machine understandable code which is then executed. Request your thoughts on this.

WordPress/ Woo commerce plugin

Wed, 11/15/2017 - 10:57

I am working on a project called which sells sarees ( An Indian dress ). the problem I faced is the customer wants to save her body dimensions{they have more than one value} in the account so when she buys a saree we can send the blouse with her sizes.

So is there any plugin [ paid / Free ] where I can add a new tab in my account area like my dimensions so the user can add her dimension there and save.