Q:

Threejs PlaneGeometry doesn't receive shadows or reflections

I'm pretty new to 3d and to threejs and I can't figure out how I can get a PlaneGeometry to show individually illuminated polygons i.e. receive shadows or show reflection. What I basically do is taking a PlaneGeometry applying some noise to every z value of the vertices. Then I have a simple directional light in my scene which is supposed to make the emerging noise pattern on the plane visible. I tried different things like plane.castShadow = true or renderer.shadowMapEnabled = true without success. Am I just missing a simple option or is this way more complicated than I think?
Here's are the relevant pieces of my code
renderer.setSize(width, height);
renderer.setClearColor(0x111111, 1);

...

var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.9);
directionalLight.position.set(10, 2, 20);
directionalLight.castShadow = true;
directionalLight.shadowCameraVisible = true;

scene.add( directionalLight );

var geometry = new THREE.PlaneGeometry(20, 20, segments, segments);

var index = 0;
for(var i=0; i < segments + 1; i++) {
    for(var j=0; j < segments + 1; j++) {

        zOffset = simplex.noise2D(i * xNoiseScale, j * yNoiseScale) * 5;
        geometry.vertices[index].z = zOffset;

        index++;
    }
}

var material = new THREE.MeshLambertMaterial({
    side: THREE.DoubleSide,
    color: 0xf50066
});

var plane = new THREE.Mesh(geometry, material);
plane.rotation.x = -Math.PI / 2.35;
plane.castShadow = true;
plane.receiveShadow = true;
scene.add(plane);

This is the output I get. Obviously the plane is aware of the light because the bottom side is darker than the upper side but there is no sign of any individual polygons receiving individual lightening and no 3d structure is visible. Interestingly when I put in a different geometry like a BoxGeometry individual polygons are illuminated individually (see 2nd image). Any ideas?

A:

Ok I figured it out thanks to this post. The trick is to use the THREE.FlatShading shader on the material. Important to note is that after every update of the vertices two things need to be done. Before rendering geometry.normalsNeedUpdate must be set to true so the renderer also incorporates the newly oriented vertices. Also geometry.computeFaceNormals() needs to be called before rendering because when you alter the vertices the normals are not the same anymore.


Q:

sharepoint copy a list to a different web

how can i copy a sharepoint list with all its data to a different web?
is there an stsadm command to do this?
or even through the gui.

A:

What you can do is Save that List as Template with the contents included and create a List Based on the save template.
To Save the List as Template you need to navigate to the List Settings Page and Select Save as Template, check the "include content" check box. Enter a Name for the template and say Okay. Next time when you try to create the list you will see the saved template and you can create list using that.
You can also take that saved template from the List Template Gallery and add it to different application / site collection.

A:

You can also do this with Gary LaPointe's stsadm extensions. They're pretty sweet. Specifically, look into the gl-copylist command.


Q:

Help explaining symbols as hash values in Ruby?

Total Ruby noob. I'm going through Zed Shaw's LRTHW, and I'm stuck on the Hash exercise. I can't make any sense of this code, and can't find anything on the web that looks like it.
cities = {'CA' => 'San Francisco', 'MI' => 'Detroit', 'FL' => 'Jacksonville'}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

def find_city (map, state)
  if map.include? state
    return map[state]
  else
    return "Not found."
  end
end

cities[:find] = method(:find_city)

while true
  print "State? (Enter to quit) "
  state = gets.chomp

  break if state.empty?

  puts cities[:find].call(cities, state)
end

Basically, I'm just stuck. I can't make the connection between how I type in a state and it returns the city. Any dumbed down explanation would be greatly appreciated.

A:

Here there are a hash (cities) with 3 pairs key => value
cities = {'CA' => 'San Francisco', 'MI' => 'Detroit', 'FL' => 'Jacksonville'}

You can access that values by the key:
puts cities['CA']  #=>  'San Francisco'

Now we add two new pairs.
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

The whole hash will be:
p cities #=> {'CA' => 'San Francisco', 'MI' => 'Detroit', 'FL' => 'Jacksonville', 'NY' => 'New York', 'OR' => 'Portland'}

Now it's defined a method called find_city. It takes a hash and a key.
def find_city (map, state)
  # if hash has the key, return its value. (There are better ways to do it.)
  if map.include? state
    return map[state]
  else
    return "Not found."
  end
end

Here there is the worst piece of Ruby code I've ever seen.
cities[:find] = method(:find_city)

Ok, that code gets the method find_city and turns it into a Method object, which could be assigned to a variable. BUT, instead of using a normal local variable, it is stored in a value of the cities hash!
That object is similar to a method, but it's an object instead of a method, and it must be called with call (in Ruby 1.8.7).
I will use a variable called my_meth (it could be any name) to explain better.
# get the method find_city and turns it into an object assigned to my_meth
my_meth = method(:find_city)

while true
  print "State? (Enter to quit) "
  state = gets.chomp

  break if state.empty?

  # here we use find_city on the cities hash.
  puts my_meth.call(cities, state)
end

puts my_meth.class

But, instead to use a variable, the original code stored the Method object on the cities hash. So, cities will be:
cities[:find] = method(:find_city)
p cities #=> {'CA' => 'San Francisco', 'MI' => 'Detroit', 'FL' => 'Jacksonville', 'NY' => 'New York', 'OR' => 'Portland', :find => (the Method object)}

So, you can access the find_city thru cities[:find].call.


Q:

Convert object with one property into parent property

I have converted javascript object from xml, this is example of object:
{
name: 'current name',
  attr1: 'attribute1',
  attr2: 'attribute2',
  address: {
    name: 'name1',
    value: {
      value: '12'
    },
    attr3: {
      name: 'no name',
      attr4: {
        attr4: 'attribute4'
      }
    }
  },
  price: {
    price: '500'
  },
  in_house: {
    in_house: '2'
  }
}

how I can convert into this:
{
name: 'current name',
  attr1: 'attr1',
  address:{
    name: 'name1',
    value: '12',
    attr3: {
      name: 'no name',
      attr4: 'attribute3'
    }
  }
  attr2: 'attr2',
  price: 500,
  in_house: 2
}

need convert all unusefull object into property, example
    {
      price :
        price: '500'
    }
    into
    { price: '500'}

A:

You could use an iterative, recursive approach for the keys and their values.

function moveUp(object, last) {
    var keys = Object.keys(object);

    if (keys.length === 1 && keys[0] in last) {
        last[keys[0]] = object[keys[0]];
        if (last[keys[0]] !== null && typeof last[keys[0]] === 'object') {
            moveUp(last[keys[0]], last);
        }
        return;
    }
    keys.forEach(function (k) {
        if (object[k] !== null && typeof object[k] === 'object') {
            moveUp(object[k], object)
        }
    });
}

var object = { name: 'current name', attr1: 'attribute1', attr2: 'attribute2', address: { name: 'name1', value: { value: '12' }, attr3: { name: 'no name', attr4: { attr4: 'attribute4' } } }, price: { price: '500' }, in_house: { in_house: '2' }, test: { test: { test: { banane: 42 } } } };

moveUp(object);

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Q:

Japanese fonts in a Java GUI

Is it possible to write a GUI in Java that would display Japanese fonts correctly regardless of the language settings of the OS it's being run on?
I'd like to write a program which is able to do this but I'm not sure how to start going about this. Any advice would be a huge help!

A:

The language settings aren't the problem here. Fonts are.
Java certainly can handle Japanese text, no matter what the system settings are, if the developer doesn't fall into the trap of depending on the platform default encoding by using things like FileReader, or new String(byte[]).
But to actually display the Japanese text, you need a font that has Japanese characters, and fonts are not part of Java. Depending on the OS, Japanese-capable fonts may be part of the default installation, or the user may be prompted to install them as needed, or they may have to be installed manually.

A:

Java can easily display Japanese regardless of if the OS has the fonts installed or not, but this is only for Swing applications. Anything using the console window requires fonts installed in the OS.
Steps:
1) Download one of the truetype fonts from here : http://www.wazu.jp/gallery/Fonts_Japanese2.html
2) Use the following code to allow your swing clients to use your fonts:
InputStream fontStream = getClass().getResourceAsStream("/locationoffontonclasspath/myfontname.ttf");
Font japaneseEnabledFont = null;
boolean japaneseDisplayEnabled = false;
try {
    japaneseEnabledFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
    GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(japaneseEnabledFont);
    japaneseDisplayEnabled = true;
} catch (Exception e) {
    // handle exceptions here
} finally {
    if (fontStream != null) {
        try {fontStream.close();} catch (Exception e1) {}
    }
}

if (japaneseDisplayEnabled) {
   .....
}

Also, if you wish to use Japanese literals in your sourcecode you have to compile with -Dfile.encoding=utf-8. If using an IDE to compile then you can change the settings on the following screen (right click the project and select properties to get this window): screenshot
More information is available at this page

A:

You can package a TrueType font with your program and load and use it in Swing components like so:
// Create a label in Japanese.
String message = "かつ、尊厳と権利とについて平等である。";
JLabel label = new JLabel(message);

// Load the TrueType font with Japanese characters and apply it.
File file = new File("msmincho.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
font = font.deriveFont(Font.PLAIN, 14f);
label.setFont(font);

Be careful to use the correct charset.  If compiling Japanese characters in the code you should compile with javac -encoding utf-8 Foo.java.  Also be sure to use the charset explicitly when using Readers.


Q:

Rails helper file for a namespaced controller?

I have a controller "ott_controller.rb" in the folder "api".
My routes look like this:

  map.namespace :api, :path_prefix => 'api' do |api|
    api.connect 'ott/playlists/:id.xml', :controller => 'ott', :action => 'playlists', :conditions => { :method => :get }
  end

I'm trying to create a helper file for this, but I can't get it to pick up.
In the helpers folder, I've tried the following

File "ott_helper.rb" with module "OttHelper"
File "api_ott_helper.rb" with module "OttHelper"
File "ott_helper.rb" with module "Api::OttHelper"
File "api_ott_helper.rb" with module "Api::OttHelper"

None of those work.
This is a rails 2 project.
Any ideas?

A:

Did you namespace the helper file as well? This should work:
app/helpers/api/ott_helper.rb
In the file:
module Api::OttHelper


Q:

Deploying my magento site on new Elastic Beanstalk environment

We have a t1.micro ec2 server right now. It has magento installed on it, which has been customized w various plugins and other custom development
I’ve successfully set up an elastic beanstalk LAMP environment and connected it to RDS.
I’d like to install our magento site on our elastic beanstalk environment and use it as our production environment, but am not sure how.
I know that deploys are handled on elastic beanstalk by uploading a zip file, but I have been unsuccessful so far at deploying working software.  I am not sure exactly what needs to be zipped, and I am not sure if I am missing/copying config files unnecessarily.
To this point I have:
Replicated the database from the t1.micro server into the RDS database.  Based on a few queries and browsing the tables, it seems like I did this successfully.
Zipping everything in our t1.micro /var/www/html folder (changing params in local.xml to RDS db host,user,pw), and uploading that folder, but am getting a stack trace:

Also - I originally had installed the sample elastic beanstalk test software successfully, so I know that there are no security group issues between my servers and RDS.
Ultimately, I would love some help on how to deploy customized magento to elastic beanstalk - what files & directories need to be included in the zip, and guidance on what files need to be changed. Any help for a n00b would be greatly appreciated!

A:

The issue was that I had created a backup of my local.xml prior to making my changes and magento was loading both files.  I deleted the backup, and everything worked.  Found answer here:
https://stackoverflow.com/questions/11143060/move-magento-installation-to-new-server


Q:

Data Loss reading from one file, processing and writing to another? Python

I wrote a script to transform a large 4MB textfile with 40k+ lines of unordered data to a specifically formatted and easier to deal with CSV file.
Problem:
Analyzing my file sizes, it appears i've lost over 1MB of data (20K Lines | edit: original file was 7MB so lost ~4MB of data), and when I attempt to search specific data points present in CommaOnly.txt in sorted_CSV.csv I cannot find them.
I found this really weird so.
What I tried:
I searched for and replaced all unicode chars present in the CommaOnly.txt that might be causing a problem.. No luck!
Example: \u0b99 replaced with " "
Here's an example of some data loss
A line from: CommaOnly.txt
name,SJ Photography,category,Professional Services,
state,none,city,none,country,none,about,
Capturing intimate & milestone moment from pregnancy and family portraits to weddings

Sorted_CSV.csv
Not present.

What could be causing this?
Code:
import re
import csv
import time

# Final Sorted Order for all data:
#['name',   'data',
# 'category','data',
# 'about',  'data',
# 'country', 'data',
# 'state',   'data',
# 'city',   'data']

    ## Recieves String Item, Splits on "," Delimitter Returns the split List
def split_values(string):
    string = string.strip('\n')
    split_string = re.split(',', string)
    return split_string

    ## Iterates through the list, reorganizes terms in the desired order at the desired indices
    ## Adds the field if it does not initially
def reformo_sort(list_to_sort):
    processed_values=[""]*12
    for i in range(11):
        try:
            ## Terrible code I know, but trying to be explicit for the question
            if(i==0):
                for j in range(len(list_to_sort)):
                    if(list_to_sort[j]=="name"):
                        processed_values[0]=(list_to_sort[j])
                        processed_values[1]=(list_to_sort[j+1])
                            ## append its neighbour

                ## if after iterating, name does not appear, add it.
                if(processed_values[0] != "name"):
                    processed_values[0]="name"
                    processed_values[1]="None"

            elif(i==2):
                for j in range(len(list_to_sort)):
                    if(list_to_sort[j]=="category"):
                    processed_values[2]=(list_to_sort[j])
                    processed_values[3]=(list_to_sort[j+1])

                if(processed_values[2] != "category"):
                    processed_values[2]="category"
                    processed_values[3]="None"

            elif(i==4):
                for j in range(len(list_to_sort)):
                    if(list_to_sort[j]=="about"):
                        processed_values[4]=(list_to_sort[j])
                        processed_values[5]=(list_to_sort[j+1])

                if(processed_values[4] != "about"):
                    processed_values[4]="about"
                    processed_values[5]="None"

            elif(i==6):
                for j in range(len(list_to_sort)):
                    if(list_to_sort[j]=="country"):
                        processed_values[6]=(list_to_sort[j])
                        processed_values[7]=(list_to_sort[j+1])
                if(processed_values[6]!= "country"):
                    processed_values[6]="country"
                    processed_values[7]="None"

            elif(i==8):
                for j in range(len(list_to_sort)):
                    if(list_to_sort[j]=="state"):
                        processed_values[8]=(list_to_sort[j])
                        processed_values[9]=(list_to_sort[j+1])

                if(processed_values[8] != "state"):
                    processed_values[8]="state"
                    processed_values[9]="None"

            elif(i==10):
                for j in range(len(list_to_sort)):
                    if(list_to_sort[j]=="city"):
                        processed_values[10]=(list_to_sort[j])
                        processed_values[11]=(list_to_sort[j+1])

                if(processed_values[10] != "city"):
                    processed_values[10]="city"
                    processed_values[11]="None"
        except:
            print("failed to append!")
    return processed_values

    # Converts desired data fields to a string delimitting values by ','
def to_CSV(values_to_convert):
    CSV_ENTRY=str(values_to_convert[1])+','+str(values_to_convert[3])+','+str(values_to_convert[5])+','+str(values_to_convert[7])+','+str(values_to_convert[9])+','+str(values_to_convert[11])
    return CSV_ENTRY

with open("CommaOnly.txt", 'r') as c:
    print("Starting.. :)")

    for line in c:
        entry = c.readline()
        to_sort = split_values(entry)
        now_sorted = reformo_sort(to_sort)
        CSV_ROW=to_CSV(now_sorted)
        with open("sorted_CSV.csv", "a+") as file:
            file.write(str(CSV_ROW)+"\n")

print("Finished! :)")
time.sleep(60)

A:

I've rewritten the main loop that seems fishy to me, using csv package.
Your reformo_sort routine is incomplet and syntaxically incorrect, with empty elif blocks and missing processing, so I got incomplete lines, but that should work much better than your code. Note the usage of csv, the "binary" flag, the single open in write mode instead of open/close each line (much faster) and the 1-out-of-2 filtering of the now_sorted array.
with open("CommaOnly.txt", 'rb') as c:
    print("Starting.. :)")
    cr = csv.reader(c,delimiter=",",quotechar='"')
    with open("sorted_CSV.csv", "wb") as fw:
        cw = csv.writer(fw,delimiter=",",quotechar='"')

        for to_sort in cr:
            now_sorted = reformo_sort(to_sort)
            cw.writerow(now_sorted[1::2])


Q:

hwo to split dataframe into equal number of subset in python

I have a dataframe
import pandas as pd
d = {'user': [1, 1, 2,2,2,2 ,2,2,2,2], 'friends':
[1,2,1,5,4,6,7,20,9,7]}
df = pd.DataFrame(data=d)

I try to split the df into several n pieces in a loop. For example, for n=3
n=3
for i in range(3):
   subdata = dosomething(df)
   print(subdata)

the output will be someting like
# first loop
   user friends
0   1   1
1   1   2
2   2   1
3   2   5

# second loop
   user friends
0   2   4
1   2   6
2   2   7
3   2   20

#third loop
   user friends
0   2   9
1   2   7

A:

You can use iloc and loop through the dataframe, put each new dataframe in a dictionary for recall later.
dfs = {}
chunk = 4

Loop through the dataframe by chunk sizes. Create df and add to dict.
for n in range((df.shape[0] // chunk + 1)):
    df_temp = df.iloc[n*chunk:(n+1)*chunk]
    df_temp = df_temp.reset_index(drop=True)
    dfs[n] = df_temp

Use this if statement for any left over rows at the end.
if df.shape[0] % chunk != 0:
    df_temp = df.iloc[-int(df.shape[0] % chunk):]
    df_temp = df_temp.reset_index(drop=True)
    dfs[n] = df_temp
else:
    pass

Access the dataframes in the dictionary.
print(dfs[0])

   user  friends
0     1        1
1     1        2
2     2        1
3     2        5

print(dfs[1])

   user  friends
0     2        4
1     2        6
2     2        7
3     2       20

print(dfs[2])

   user  friends
0     2        9
1     2        7


Q:

Re-render Blaze template on text change

I have a Meteor Blaze Template based on autoform.
<template name="patientForm">

    {{#autoForm id="insertUpdatePatientForm" collection="Patients" doc=selectedPatientDoc
    type=formType validation="browser" template="semanticUI"}}

    {{> afQuickField name="firstName"}}
    {{> afQuickField name="lastName"}}

   {{> afQuickField name="phn.type"}}
   {{> afQuickField name="phn.value" class="ramq"}}

        {{> afQuickField name="birthDate"}}
        {{> afQuickField name="gender"}}

    <button class="ui submit button" type="submit">Save</button>

    {{/autoForm}}

</template>

I want to handle the text change event for input with name phn.value. Based on the text, I want to auto-populate two other fields: gender and date of birth. I am doing it by changing the template data directly as follows:
Template.patientForm.events({
    'change .ramq': function changeRAMQ(event, templateInstance) {
        const { patient } = templateInstance.data;
        if (patient.phn.type === 'RAMQ') {
            const ramq = event.target.value;
            const yy = parseInt(ramq.substr(4, 2), 10);
            let mm = parseInt(ramq.substr(6, 2), 10);
            const dd = parseInt(ramq.substr(8, 2), 10);
            patient.gender = mm < 13 ? 'Male' : 'Female';
            if (mm > 50) {
                mm -= 50;
            }
            patient.birthDate = moment(new Date(yy, mm, dd)).format('YYYY-MM-DD');
        }
    },
});

I am getting the template data and directly modifying the gender and birthdate when the phn.value changes. However, the modified gender and birthdate does not re-render in the autoform / blaze template. Any way by which I can force re-render of Blaze template or alternate ways to effect changes to other controls in Blaze template?

A:

To enable reactivity and thus the re-rendering of the fields you should use a ReactiveVar (or ReactiveDict)
You can do this like this:
Template.patientForm.onCreated(function(){
  const instance = this;
  instance.birthDate = new ReactiveVar()
});

And in your helpers and events you can use instance.birthDate.set() / get()
Template.patientForm.helpers({
   birthDate() {
      return Template.instance().birthDate.get()
   }
});

Template.patientForm.events({
   'click something'(event, instance){
   ....
     instance.birthDate.set(value);
   ....
   }
});


Q:

Not able to dynamically set color of Vue avatar with style property

I am trying to dynamically set the background-color property of my Vuetify avatar but it does not seem to working. I do not want to use the color property. I have to use the background-color definition.
here is a codepen showing my issue https://codepen.io/entropy283/pen/VweWvoG?editors=1010

A:

you must use :style syntax to bind the styles properly, this allows to use JS to call the function

  <v-app id="inspire">
    <v-row justify="space-around">

      <v-avatar style="background-color: bisque;">
        CJ
      </v-avatar>

      <v-avatar :style="{ backgroundColor: getcolor('ngae')}">
        CJ
      </v-avatar>

      <v-avatar :color="getcolor('name')">
        CJ
      </v-avatar>

    </v-row>
  </v-app>

You can read about style bindings here


Q:

GeoPandas: plot two layers but only to the extent of the smaller one

I am using GeoPandas and I want to plot two layers. I want the map to have the extent of the smaller layer. With this code below, the map's size automatically fits the bigger layer.
import geopandas as gp
import matplotlib.pyplot as plt
from shapely.geometry import LineString
from shapely.geometry import MultiPoint

thesmallpoints=gp.GeoDataFrame([[MultiPoint([(0, 0), (1, 1), (1,2), (2,2)])]],columns=['geometry'])
thelargeline=gp.GeoDataFrame([[LineString([(0, 0), (1, 1), (1,2), (20,20)])]],columns=['geometry'])

base=thesmallpoints.plot(marker='o', color='blue', markersize=20)
thelargeline.plot(ax=base, color='green')
plt.show()

How can this be achieved?

A:

You can set limits to the axis without chaining original GDF.
import geopandas as gp
import matplotlib.pyplot as plt
from shapely.geometry import LineString, MultiPoint, Polygon

thesmallpoints=gp.GeoDataFrame([[MultiPoint([(0, 0), (1, 1), (1,2), (2,2)])]],columns=['geometry'])
thelargeline=gp.GeoDataFrame([[LineString([(0, 0), (1, 1), (1,2), (20,20)])]],columns=['geometry'])

minx, miny, maxx, maxy = thesmallpoints.geometry.total_bounds

f, ax = plt.subplots()
thesmallpoints.plot(ax=ax, marker='o', color='blue', markersize=20)
thelargeline.plot(ax=ax, color='green')
ax.set_xlim(minx - .1, maxx + .1) # added/substracted value is to give some margin around total bounds
ax.set_ylim(miny - .1, maxy + .1)
plt.show()


Q:

connect sql server 2005/2008 over internet

How do I connect to SQL Server 2005/2008 using Management Studio or other desktop application over the internet?

A:

Check out WCF Data Services:
http://msdn.microsoft.com/en-us/data/bb931106.aspx
That way, you don't have to totally expose your database server out to the internet, but you get fine grained control over what gets exposed and who (which type of user) can see or modify what.
Marc


Q:

How Can I Make Flour More White When Under Process In Flour Mill

My father is a flour miller. He wants to know how he can make wheat, or flour more specifically, whiter during the milling process. Is there anything that can be done before in preparation or after the process?

A:

Flour will whiten over time when stored. It generally takes several months to get a whiter color. Most flour manufacturers wish to speed this process up and so they actually bleach the flour using cholrine or benzoyl peroxide. This bleaching process also removes nutrietns which is why flour in the U.S. that has been bleached must also be "fortified" by having nutrients added back in.
There isn't much you can do beforehand. After milling, you can either bleach for immediate affect or store and allow it to whiten naturally. Keep in mind that different flours are usually bleached with different chemicals depending on what you plan to do with the flour.
I'll leave it to you to decide if it's worth the time and nutritional value to mix chemicals in to your flour for what is purely a cosmetic benefit.


Q:

Can I construct a citadel next to the borders of a city state?

The description for "Constructing a Citadel" says that "If the new culture border claims hexes owned by another Civilization, you will incur a diplomatic penalty as a result."
Does this apply to city states? Are they counted as Civilizations?

A:

Yes, you can use a Citadel to steal tiles from an adjacent city state.
Just like with civilizations, doing so will result in a diplomacy hit, though unlike full civilizations, City States are much easier to bribe back into their good graces.
You will lose 50 influence if you are not allied with the City State. If you are allied, you will not lose any influence at all.


Q:

textbook accusations -- meaning?

Putin has instilled fear of stepping out of line with talk from his propagandists about the “sixth column.” The regime has long smeared the opposition with textbook accusations of them being Russia’s “fifth column.” But the Orwellian new invention of a “sixth column” refers to those inside the regime opposing expansionism due to their ties to the West.

What does that mean?

A:

"Textbook" can be used as an adjective as well as a noun. It is meant to evoke the definition of something as it would be defined in a textbook (or in school, university, etc). More broadly:

adj. Being a characteristic example of its kind; classic: a textbook case of schizophrenia.

He's saying that the accusations are likely staple or classic examples of Russian (or European, not sure what the context is) politics.
Source: The American Heritage® Dictionary of the English Language, Fourth Edition copyright ©2000 by Houghton Mifflin Company. Updated in 2009. Published by Houghton Mifflin Company. All rights reserved.

A:

Ditto Jasper and CrazyEyes, but let me see if I can state this in a way that makes it more clear.
Suppose you were writing a beginner's textbook on, say, how to build a bookcase. Presumably you would use a simple, straightforward case: a rectangular bookshelf, all square corners, capable of supporting normal weights, etc. When you're writing a textbook, you don't normally use odd-ball examples full of special cases. At least you don't start with those. Like in my "bookcase" example, you probably wouldn't use a bookshelf capable of supporting 6,000 pounds of books, with some of the books 3 meters tall, and some of them triangular and others round. You'd deal with normal sizes and weights.
Thus, when we are discussing something that is the normal, simple case, no unusual or extreme requirements, everything pretty much typical, maybe even over-simplified, we call it a "textbook example". In real life, professionals expect to at least occasionally run into problems that don't fit the standard textbook example. Then they will have to use some creativity and original thinking to solve the problem. Thus, by extension a "textbook example" is one that does not require any creativity: it's the standard case, exactly the way people having been doing this for many years.
So what the writer is saying here is that these accusations are the sort of accusations that you would find in a text -- the normal, standard, by-the-book case. Putin didn't have to be clever or original to come up with these accusation: they're the sort that propagandists have been using for hundreds of years. The idea is that he could almost have taken any textbook on "how to smear your political opponents" off the shelf and copied them out, just filling in the names of the right people or groups where it says "fill in opponent's name here".


Q:

Django & Pandas: Get Choice Value in dataframe instead of Choice label

Again with a question regarding django... and pandas.
I'm trying to get the value of two 'choices' column into a pandas dataframe; however, I'm only getting the label of the choice.
Example code:
my_app/models.py
class Entry(models.Model):
    STATUS_ONE = 1
    STATUS_TWO = 2

    STATUS_CHOICES = (
        (STATUS_ONE, 'Status one'),
        (STATUS_TWO, 'Status two')
    )

    status = models.IntegerField(choices=STATUS_CHOICES, default=STATUS_ONE)
    status_date = models.DateTimeField(auto_now=True)
    contents = models.TextField()

The data I'm getting:
from django_pandas import read_frame
from my_app.models import Entry
qs = Entry.objects.all()
df = read_frame(qs)
df
#      status                 status_date        contents
#  Status one   2018-04-30 20:00:00+00:00   Test contents
#  Status two   2018-04-30 21:00:00+00:00   More contents

What I'd like to get is:
#      status                 status_date        contents
#           1   2018-04-30 20:00:00+00:00   Test contents
#           2   2018-04-30 21:00:00+00:00   More contents

Is there a way to get it?

A:

I've got it!
I simply need to add the verbose=False option to read_frame, and that's it:
df = read_frame(qs, verbose=False)


Q:

Get distinct value from comma seperated array using LINQ

Supposed I have a string array like this

{
"A“，
”B",
"A,B,D",
"C"
}

Is it possible that I write a single LinQ to get the distinct values {"A","B","C","D"} into a List?

A:

lists.SelectMany(l => l.Split(',')).Distinct().ToList();

A:

var distinctValues = myList.SelectMany(x => x.Split(',')).Distinct().ToList();

This will split each string, and then flatten them into a single list, and get the distinct elements.
If you want to get the elements in alpha order, then you can tack on a .OrderBy(x => x) right before .ToList().


Q:

How to make Android Webview Background Transparent at KITKAT(4.4)

Recently, I implement webbased-application on Android.
I want to make webview's background color Transparent.
Searching, i've found that two lines for Webview.
newWebView.setBackgroundColor(0x00000000);
newWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

It works for Android version 4.0~4.3, but does not work for 4.4 KITKAT.
I got just white-background.
Addtionally, when i set background color, black, shown below :
newWebView.setBackgroundColor(Color.BLACK);

Also I saw white-background.
Is there anybody knows the solution ?

A:

This might help you
    webView.setBackgroundColor(0x00000000);
if (Build.VERSION.SDK_INT >= 11) webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

this.wv.setWebViewClient(new WebViewClient()
{
    @Override
    public void onPageFinished(WebView view, String url)
    {
        view.setBackgroundColor(0x00000000);
        if (Build.VERSION.SDK_INT >= 11) view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    }
});

Source : http://premius.net/blog/andoid/118-android-webview-transparent-background-for-android-2-3-and-4-x.html


Q:

Angularjs remove button not working

i am building a shopping app. Somewhere in the app i need to show the user’s shopping cart and let him edit it.
I have remove button but not working...

<title>Your Shopping Cart</title>

Your Order

    {{item.title}}
    <input ng-model="item.quantity" />
    {{item.price | currency}}
    {{item.price * item.quantity | currency}}
    <button ng-click="remove($index)">Remove</button>

A:

Move your $scope.remove inside the CartController's { }


Q:

Formatting text in tableView Cell

I want "\(category.questionCount) Questions" text to be aligned right, while
"\(category.categoryName)  >  \(category.subCategoryName)" text to be aligned left.
NOTE: In this case, not sure left alignment is necessary.
cell.titleL?.text = "\(category.categoryName)  >  \(category.subCategoryName) \(category.questionCount) Questions"

A:

You should be using two labels, not one. If a text is too long, you can set firstLabel.numberOfLines=0, set secondLabel alignment to right.


Q:

How do I change the minimum working frequency?

The file
/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_frequency

reads a value of 800 Mhz. The powertop tool also suggested that 800 Mhz w3as the minimum frequency being used.
I changed the above-mentioned file to 1.6 GHz and monitored powertop tool again. To my surprise, it still said that the minimum frequency was 800 MHz instead of 1.6 GHz.

A:

Run the following command:
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor

Its output is probably one line for each core/cpu that you have saying ondemand. This means that when the CPU is not in use, it will go back to the lowest speed.
Btw, the files /sys/devices/system/cpu/cpu*/cpufreq/scaling_available_governors will tell you the available governors and you can take a look at governors.txt to see the behavior of each of them.
You will have to first set the appropriate governor and then set the desired speed.


Q:

Auto refresh after 5 min

I'm trying to get the implantation for auto refresh on my project which is chat bot. When the chat page is open and a conversation is loaded, I should periodically refresh the conversation entries list.
By default, every 5 seconds.

If there are no additional conversation entries on a refresh, we should increment the wait time by 5 seconds, up to a maximum of 120 seconds.
If there are additional conversation entries on a refresh, we should reset the wait time to 5 seconds.

A:

var delayTime = 5000;
    function refresh() {
        if(chatid.length > 0) {
        ChatService.getChatDetailsById(chatid)
            .then(function (result) {
                if (result.Data.Messages.length > $scope.chatDetails.Messages.length) {
                    getChatDetails(chatid)
                    delayTime = 5000;
                } else {
                    increseDelay();
                }
                timeout();
            });
            function increseDelay() {
                if (delayTime !== 120000)
                    delayTime += 5000;
            }
        }
    }
    function timeout() {
        setTimeout(function () {
            refresh();
        }, delayTime);
    };
    timeout();


Q:

How do I populate my UITableView with Facebook Profile Photos

I've been stuck on this for days and after searching high and low for answers on Stackoverflow and looking through code on GitHub, I'm at my wits end.
I'm trying to get a Facebook Profile picture to show up with other data in a UITableView.  I'm using the following code.  The score shows up, the Facebook profile name shows up, but the image does not show.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

    [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"%@/scores?fields=score,user", appID] parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {

        if (result && !error)
        {
            for (NSDictionary *dict in [result objectForKey:@"data"])
            {
                NSString *name = [[dict objectForKey:@"user"] objectForKey:@"name"];
                NSString *strScore = [dict objectForKey:@"score"];
                NSString *profilePictureID = [[dict objectForKey:@"user"] objectForKey:@"id"];
                NSString *profilePicture = [NSString stringWithFormat:@"%@/picture?width=80&height=80&redirect=false",profilePictureID];
                NSString *url = [[NSString alloc] initWithFormat:@"https://graph.facebook.com/%@/picture",profilePictureID];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
                NSLog(@"The URL is %@.  The image URL is %@", url, image);
                [url release];
                NSLog(@"This message is in the UITableViewCell and will hopefully show the name %@ and the score %@ along with %@ as the profile picture URL.", name, strScore, profilePicture);

                // DID NOT WORK - cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", image]];
                // DID NOT WORK - cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", profilePicturel]];

                cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", url]];

                cell.textLabel.text = [NSString stringWithFormat:@"%@", name];
                cell.detailTextLabel.text = [NSString stringWithFormat:@"Score: %@", strScore];

            }
        }

    }];

    return cell;
}

My NSLog messsages are returning the following data.
- The URL is https://graph.facebook.com/xxxxx/picture.  The image URL is <UIImage: 0xdee1234>

- This message is in the UITableViewCell and will hopefully show the name xxxxx and the score xxxxx along with xxxxx/picture?width=80&height=80&redirect=false as the profile picture URL.

I've tried a dozen different ways to get the Facebook profile photos to work and I thought this one would considering it is the first time that I got back a log message like this.
I would appreciate any help or suggestions on how to get this working.  Thanks!

A:

You have already retrieved the image (if it exists) with this line:
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];

So all you need to do is set it:
cell.imageView.image = image;

The method imageNamed: is only needed if you are trying to load an image from a file in your project.
One thing to note though, NSData's dataWithContentsofURL: method is synchronous. You are going to be blocking the main thread with this approach. You'd be better off doing all of this work first, storing the data in an array, and then reloading the tableView using that array as the data source.


Q:

Vertex color value has weird offset in value when assigned from script

What might explain this difference in values?
mesh.vertex_colors.active.data[loop_index].color[3] = colorItem.alpha
print(str(colorItem.alpha) + " / " + str(mesh.vertex_colors.active.data[loop_index].color[3]))

outputs
0.03125 / 0.0313725508749485

A:

Looking at the blender sources, the colors seem to get rounded.
static void rna_MeshLoopColor_color_set(PointerRNA *ptr, const float *values)
{
  MLoopCol *mlcol = (MLoopCol *)ptr->data;

  mlcol->r = round_fl_to_uchar_clamp(values[0] * 255.0f);
  mlcol->g = round_fl_to_uchar_clamp(values[1] * 255.0f);
  mlcol->b = round_fl_to_uchar_clamp(values[2] * 255.0f);
  mlcol->a = round_fl_to_uchar_clamp(values[3] * 255.0f);
}


Q:

Manipulating classes with event listeners in Angular

I'm trying to make a github search app with the GitHub API and I have some problems with manipulation. What I need is when user types something in the search bar, div container should be remove from the page. I know how to do it with html and javascript, but I'm new to Angular. I read the documentation and watched some tutorials but I couldn't figure out how to do it.
home.component.html:
<input type="text" [(ngModel)]="profile" (keyup)="findProfile()" placeholder="Enter the username..." class="input">

  <ng-template [ngIf]="profile !== '' && user">

Username: {{user.login}}

Location: {{user.location}}

E-mail: {{user.email}}

Blog Link: {{user.blog}}

Member Since: {{user.created_at}}

    <button [routerLink]="['', user.login.toLowerCase(), user.id ]" class="viewProfileButton">View Profile</button>

    <button (click)="localStorage()" class="viewProfileButton">Add to Favorite</button>
  </ng-template>

  <ng-template [ngIf]="displayData !== undefined && displayData">
      <button (click)="consoleLog()">consoleLog</button>

Username: {{displayData.login}}

Location: {{displayData.location}}

    <button (click)="removeLocal()" class="viewProfileButton">Remove Favorite</button>
  </ng-template>

<button (click)="consoleLog()" class="viewProfileButton">Console Log</button>
<router-outlet></router-outlet>

A:

Try this
html
<input type="text" [(ngModel)]="profile" (ngModelChange)="detectChange($event)" (keyup)="findProfile()" placeholder="Enter the username..." class="input">

   //your code

ts
closeDiv: boolean = true;

detectChange(ev: any) {
    if(ev.length > 0){
        this.closeDiv = false;
    }else {
       this.closeDiv = true;
    }
}


Q:

How can a parent remain sane? How do you keep your energy and temper?

I'm sure every parent has days like this:

Your child has been a troublemaker all day. You are exhausted, and at your wits' end. It would be nice to just take a break, to have someone else take over for an hour - or a day. But you're alone and the partner is at work for another "X" hours. The weather is bad; you can't go to the playground or zoo.
You feel like screaming.

What would you do to keep sane? Let's hear some ideas.
Update:
"Taking a break" is what I'd do too, but sometimes it's not easy. My reference situation is a toddler -- too young to be "parked" in front of a TV, and too old to be placed in a crib. Lock him in his room? Doesn't feel right.

A:

Get out of the house. Put raincover on a stroller and just walk around.
Go to library - this is the best. In US they often have a space for kids with toys and baby books.
Go to the mall.
IKEA (if you have one around) might have a playspace for small kids.
Go to the indoor playground.
There is got to be a toy which will keep him busy for a while, for my son it was Thomas the Train Engine simple set. Activity table kept him busy for some time as well.
Get out a new toy.
Have a schedule - this way instead of one long day you have a series of short periods of time that is easier to survive.
Keep the nap as long as possible - it is a life saver. The days when my son napped were much easier then the ones he did not. Even if he does not nap try to put him in a crib for some time on schedule.

Edit: also, if possible, give mom a way to get out of the house to the gym or another place of her choosing on her own regularly: ask family member to babysit, hire a babysitter for several hours or stay with child by yourself on weekend.

A:

Take a break.
Our daughter must not have been more than a few months old when I just needed a break. I put her in her crib ("somewhere safe") and took a 30 minute shower. She cried. A lot. But I needed the break. It would've been worse for us had I not taken the break. Quite frankly, I don't think she cares or remembers anymore (she is 1!).
Since then, anytime I need a break and I can't find anyone else to take her for a little while - she just goes in her crib or playpen with a couple of her toys (if the weather is bad). It's easier when the weather is nicer - in the stroller and we go for a walk.
I am as much of a human as she is, and I need a break too. If I can't take care of myself, I sure as heck can't take care of her.

A:

Hide.
Seriously.  Sometimes, when things feel like they're going to spiral out of control, the best thing to do is get the kids cordoned off someplace reasonably safe, then go somewhere else (in the house or yard) and take a few minutes to calm down.
Tossing a movie on to the TV and giving the kids a large bowl of popcorn can give you just enough time to compose yourself.
If the child is an infant, sometimes all you can do is put him or her down in their crib with some toys and go into another room.  Yeah, they'll probably cry and scream, but they were doing that anyway and so were you.  Turn on some music, close the doors, and decompress.
You're not going to do your kids any favors by escalating things.


Q:

Quantum Fourier Transform and roots of unity.

I need to find $QFT_{6}$ for the state quantum state $\frac{1}{\sqrt2}(|0\rangle + |3\rangle)$. I received a very sufficient answer recently on simplifying nth roots of unity, but I am having a lot of trouble applying it to this problem. I have obtained the $QFT_6$ matrix below, and multiplied it by the shown state:
$$
\begin{pmatrix}
  \frac{1}{\sqrt6} & \frac{1}{\sqrt6} & \frac{1}{\sqrt6} & \frac{1}{\sqrt6} & \frac{1}{\sqrt6} & \frac{1}{\sqrt6}\\
  \frac{1}{\sqrt6} & \frac{1}{\sqrt6}\omega & \frac{1}{\sqrt6}\omega^2 & \frac{1}{\sqrt6}\omega^3 & \frac{1}{\sqrt6}\omega^4 & \frac{1}{\sqrt6}\omega^5\\
  \frac{1}{\sqrt6}  & \frac{1}{\sqrt6}\omega^2 & \frac{1}{\sqrt6}\omega^4 & \frac{1}{\sqrt6}\omega^6 & \frac{1}{\sqrt6}\omega^8 & \frac{1}{\sqrt6}\omega^{10}\\
  \frac{1}{\sqrt6}  & \frac{1}{\sqrt6}\omega^3 & \frac{1}{\sqrt6}\omega^6 & \frac{1}{\sqrt6}\omega^9 & \frac{1}{\sqrt6}\omega^{12} & \frac{1}{\sqrt6}\omega^{15}\\
  \frac{1}{\sqrt6}  & \frac{1}{\sqrt6}\omega^4 & \frac{1}{\sqrt6}\omega^8 & \frac{1}{\sqrt6}\omega^{12} & \frac{1}{\sqrt6}\omega^{16} & \frac{1}{\sqrt6}\omega^{20}\\
  \frac{1}{\sqrt6}  & \frac{1}{\sqrt6}\omega^5 & \frac{1}{\sqrt6}\omega^{10} & \frac{1}{\sqrt6}\omega^{15} & \frac{1}{\sqrt6}\omega^{20} & \frac{1}{\sqrt6}\omega^{25}\\
\end{pmatrix}
\begin{pmatrix}
  \frac{1}{\sqrt2}\\
  0 \\
  0 \\
  \frac{1}{\sqrt2}\\
  0 \\
  0
\end{pmatrix}
$$
Right, well now I don't understand how to just express all of the omegas in terms of $\omega$ and $\omega^2$. Help would be much appreciated.

A:

Position a regular hexagon on the unit circle with vertices at $\pm1$. Let $\zeta$ be the first complex root of unity counterclockwise from $1$. Then $\zeta^2$ is a third full rotation away from $1$, in other words it is a third root of unity. And $\zeta^3=-1$ since it sweeps out exactly half a rotation. Algebraically speaking we know $(\zeta^3)^2=1$ and $\zeta^3\ne1$ (since $\zeta$ is a primitive $6$th root) so $\zeta^3=-1$.
This tells us that $\zeta^4=-\zeta$ and $\zeta^5=-\zeta^2$. We already know $\zeta^6=1$. Can $\zeta^2$ be reduced?
Indeed it can. The theory of cyclotomic polynomials tells us that
$$\Phi_6(x)=\frac{(x^6-1)(x-1)}{(x^3-1)(x^2-1)}=\frac{x^3+1}{x+1}=x^2-x+1.$$
So $\zeta^2=\zeta-1$. Thus all of $\zeta^2,\zeta^3,\zeta^4,\zeta^5,\zeta^6$ can be written in the form $a+b\zeta$ with these relations.
One can also argue $\zeta^2=\zeta-1$ with a more geometric toolkit. Looking at the hexagon it is clear that $\zeta^2$ bisects the vectors representing $-1$ and $\zeta$, so $\zeta^2=r(\zeta-1)$ already; at this stage one shows $\zeta-1$ has modulus $1$ so $r=1$ hence $\zeta^2=\zeta-1$.
Finally with the cycling $1=\zeta^6=\zeta^{12}=\zeta^{18}=\cdots$ you should have all you need.


Q:

How to create this global constant to be shared among controllers in Angularjs?

Suppose I want to make this a variable a constant to be shared among controllers in Angularjs;
$webroot = "localhost/webroot/app"

After some investigation, it seems services are the way to do. But what is the best way? Do I use a factory, service, value or something else?
The services.js from angularjs-master-seed is below;
angular.module('myApp.services', []).value('version', '0.1');

How do I modify it to have a constant $webroot that is sharable among controllers?
Can I do the following?
angular.module('myApp.services', [])
        .value('version', '0.1')
        .constant('webroot','localhost/webroot/app');

If it is ok, how do I call it in the controller?

A:

Whats happens when you want more constants? How about adding a config object that you can inject wherever needed. As its a single file it's also much easier to have dev.config and prod.config files that can be swapped in and out at build time.
app.factory('Config', function(){
    return{
        webRoot: "localhost/webroot/app",
        moreSettings: "abc"
    };
});

A:

If your variable have a constant value or is set once value is the right choice.
You can define it like this:
app = angular.module('myApp', []);
app.value('$webroot', 'localhost/webroot/app');

Now you can inject the service to your controller and use it:
app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
  $scope.webroot = $webroot;
}]);

Edit #1
To fit your updated question: You can use a constant the same way as a value:
app = angular.module('myApp', []);
app.constant('$webroot', 'localhost/webroot/app');

app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
  $scope.webroot = $webroot;
}]);


Q:

AWS EC2: Switch Instance when status check fails

I have created two instances in AWS (one is Live & other is Backup). My website is hosted on Live Instance. what I want to do is, if Live instance Status check fails, then it should switch to Backup Instance. Is there any automated process to achieve the same?

A:

Is not a good idea to keep one instance idle and pay for it. Put them under an Elastic Load Balancer and start using both of them. The ELB health check will automatically remove the instances that stop working. Then you can continue to monitor the number of healthy instances under your ELB with AWS Cloud Watch and setup an alert - to get an email when something happens or you can even autoscale


Q:

Create PDF from UIScrollView (pages after 1st are blank)

I've been around the block on stack and google trying to get the right way to do this ironed out, any help would be great.
I can render the first page in a PDF but every other page is just blank.
I have a UIScrollView on a view controller in storyboard. I dynamically load content into that scroll view in my view controller's viewDidLoad method. After any item is added I record it's height and then set the content size height of the scroll view accordingly, so the scroll view is fine. It's content width is set to 612
Then I call a function to create a PDF:
func createPDF() {

    let pdfData = NSMutableData()

    let scrollHeigt = scrollViewForContent.contentSize.height

    let rawNumberOfPages = scrollHeigt / CGFloat(792)
    let numberOfPages = Int(ceil(rawNumberOfPages))

    var pageNumber = Int()

    let pageSize = CGSizeMake(612, 792)

    UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)
    let pdfContext : CGContextRef = UIGraphicsGetCurrentContext()

    do {

        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil)

        if pageNumber < 1 {

            scrollViewForContent.layer.renderInContext(pdfContext)

        } else if pageNumber >= 1 {

            let offsetForScroll = CGFloat(pageNumber * 792)

            scrollViewForContent.setContentOffset(CGPointMake(0, offsetForScroll), animated: false)

            CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, -offsetForScroll)

            scrollViewForContent.layer.renderInContext(pdfContext)

        }

        pageNumber++

    }
        while pageNumber < numberOfPages

    UIGraphicsEndPDFContext()

    let tempDir = NSTemporaryDirectory()

    let tempDirWithFilename = tempDir.stringByAppendingPathComponent("test1.pdf")

    pdfData.writeToFile(tempDirWithFilename, atomically: true)

    let aURL : NSURL = NSURL(fileURLWithPath: tempDirWithFilename)!

    let objectsToShare : NSArray = [aURL]

    let activityVc = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

    self.presentViewController(activityVc, animated: true, completion: nil)

}

How come the data for anything past the first page isn't being rendered? I get the correct number of pages, only the first page has any of the data. Thank you (I'm new and really appreciate you taking the time to look).

A:

You should translate the transformation matrix (CTM) of the PDF context the same amount you scroll the UIScrollView instance using the function below:
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, -offsetForScroll);

Then your call to renderInContext should function properly.
You can see this method in action by looking at the following example that takes the screenshot of the visible area at a particular offset and saves it into an image:
scrollViewForContent.setContentOffset(CGPoint(x: 0, y: shiftAmount), animated: false)

UIGraphicsBeginImageContextWithOptions(scrollViewForContent.frame.size, true, 0);

CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, -scrollViewForContent.contentOffset.y);

scrollViewForContent.layer.renderInContext(UIGraphicsGetCurrentContext())

let img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

Also, your if conditions are incorrect. Change else if pageCount > 1 to else if pageCount >= 1 so that it doesn't skip the page number 1.


Q:

Determine probability if player wins game

Two players play a game with a infinite deck of cards. This deck consisting of these types of cards:

Queen of Spades
Jack of Spades
King of Hearts
Queen of Hearts
Jack of Hearts
Two of Clubs
Three of Clubs
Four of Clubs
Five of Clubs
Six of Clubs

(There are 10 different card types)
Player 1 starts and the two players take turns. When it is $P_1$'s turn they cheat and pick 2 cards uniformly at random, and when it is $P_2$'s turn they pick 1 card uniformly at random.
If $P_1$ picks a card that is of the suit Spades $P_1$ won. If $P_2$ picks a card that is of the suit Spades or Hearts $P_2$ wins. What is the probability of $P_1$ winning what is the probability of $P_2$ winning.
I am trying to come up with formulas for these events and the sample sapce but I am stuck
I was thinking that I can do something like this in the event (A) that $P_1$ wins:
A = $P_1$ wins -> {$Not$ $Spade^n$, $Spade^m$; $n\ge0$, $m>0$}
B = $P_2$ wins -> {$Club^n$, $Spade$ $or$ $Heart^m$; $n|ge0$, $m>0$}
Any ideas if I am on the right track?

A:

For brevity, write A if Player A gets at least one spade when it is her turn, and X if she doesn't. Write B if Player B gets a spade or heart when it is her turn, and Y if she doesn't.  Then here is a beginning of the infinite list of ways Player A can win the game:
$$\text{A; XYA; XYXYA; XYXYXYA; XYXYXYXYA}$$
The probability A does not get a spade when it is her turn is $(0.8)^2$. So the probability she wins when it is her turn is $1-(0.8)^2$, which is $0.36$.
Thus $\Pr(\text{X})=0.64$. It is easy to see that $\Pr(\text{Y})=\frac{1}{2}$, so the probability of XY is $0.32$.  Thus the probability A ultimately wins  is
$$0.36+(0.32)(0.36)+(0,32)^2(0.36)+(0.32)^3(0.36)+\cdots.$$
This is an infinite geometric series, first term $0.36$, common ratio $0.32$. By a standard formula it has sum $\frac{0.36}{1-0.32}$.
Another way: We condition on the result of the first pick. Let $p$ be the probability A ultimately wins. She can win in two ways, (i) immediately or (ii) later. The probability of an immediate win is $0.36$.
Winning later happens if A and B strike out on their first turns. If that happens, A has probanility $p$ of ultimately winning. Thus
$$p=0.36+(0.32)p.$$
Solve for $p$.
Remark: The "words" for which A wins can be described in standard shorthand as $(\text{XY})^n\text{A}$, $n\ge 0$.


Q:

How to change download url path in wordpress to www.yoursite.com/download?

I am trying to hide or shorten the link to files or picture uploaded to the wp-content/uploads folder.
By default in WordPress if you upload and image, pdf, etc and insert it into a post or page it will have a link like this:
mysite.com/wp-content/uploads/2014/08/picture.jpg"
I want to hide the reference to all WP folders on my site. I am trying to find a way that the URL will display like this instead.
mysite.org/uploads/2014/08/picture.jpg"
or
mysite.org/uploads/picture.jpg"
or
mysite.org/picture.jpg"
Is there a plugin or some hack that will let me hide the "wp-content" from showing up in my urls?

A:

Add this to your wp-config.php file for your website.
define( 'UPLOADS', 'downloads' );

Then using FTP or RDP (or however you access your server), create a folder called "downloads" in the root directory of the WordPress site.
Then you need to uncheck the box for the "Organize my uploads into month- and year-based folders" option in Settings > Media of the WordPress admin.
Note: If you already have files in the media library, those will need to be moved over and all references to the old uploads folder in the database changed, if you want it all to be consistent.


Q:

App specific masterpage

Is it possible to use a separate masterpage for each app?
Because I want to use a different masterpage for an Wiki Library which should use other settings as the default Pages on my Site.

A:

You can do that from SharePoint designer. Just change the master page in view pages ex. All Items.aspx, DisplayForm.aspx and so on.
MasterPageFile="~masterurl/default.master"

In the top of the view pages, you will find above code. Now change ~masterurl/default.master with your custom master page.
MasterPageFile="{Path}/{Master Page Name}.master"


Q:

Continue with PHP or move to Java Framework

I'm building a website for my friend's startup.
I'm currently building it on PHP, MySQL, Apache. Everything is going pretty smooth till now, but one of my friend recommends i move to a Java framework because that'd be better when the site becomes bigger.
I don't have any Java Knowledge and I have adequate knowledge of PHP but I'm a fast learner
Should i continue with PHP (can PHP be used for big sites?) or should i move to a Java Framework?
Any suggestions please.

A:

PHP can be used for big sites.  Take a look at Facebook.  End of story...

A:

When someone says something like that, you need to have them justify what they are saying. PHP is scalable and versatile. Java has it's strengths and weaknesses too, just like any other programming language.
Since you are a novice in PHP, you probably won't reuse much of the code that you are using to build the initial site. I know you plan to, but the likelyhood that you will is very slim. Go with what you know.
PHP has been used by a plethora of sites. Google, Yahoo, Facebook, etc, etc all use some php for all their sites.

A:

I think regardless of whether you go with PHP or a Java solution you're going to have to learn a new set of frameworks/libraries. If you don't have experience building anything more than a toy website (including any you've done through education) there will be plenty to learn from both paths.
Research some frameworks for both PHP and Java and make up your own mind based on what you've read. If it's such a long project you'll have plenty of time to familiarise yourself with whichever option you choose.


Q:

collapse-menu отображение, прятать в мобильной версии меню при клике в любом месте

Подскажите пожалуйста, использую collapse-menu от bootstrap. Когда в режиме responsive, меню сворачивается обратно, только когда нажимаешь снова на иконке меню. Как можно сделать, чтобы оно сворачивалось при клике в любом месте экрана?
Вот html стандартный

                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                                Toggle navigation

                            </button>

Home

About me

Resources

My work

Contact me

A:

Добавить:
  $(document).on('click',function(){
    $('.collapse').collapse('hide');
  })

  $(document).on('click',function(){
$('.collapse').collapse('hide');
})

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>

       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
         Toggle navigation

       </button>

Home

About me

Resources

My work

Contact me


Q:

Covnert JSON to string in android

I am trying to get the user details using people.get in which I have emails which I need to get that value.
This is what I mean:

This is how I'm trying to do but unable to get the value
try {
            String resp =profile.getEmails().toString();
            JSONObject mainObject = new JSONObject(resp);
            JSONObject uniObject = mainObject.getJSONObject("emails");
            String  email = uniObject.getString("value");
            ((TextView) findViewById(R.id.txtemail)).setText(email);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }

Any help is appreciated.

A:

In your JSON response, emails is a JSONArray, not a JSONObject. You would need to get it like this:
JSONObject json= new JSONObject(responseString);  //your response
try {
    JSONArray responseArray = jsonObj.getJSONArray("email");
    for (int i = 0; i < responseArray.length(); i++) {
        // get value with the NODE key
        JSONObject obj = responseArray.getJSONObject(i);
        String lastName =  obj.getString("value");
        String firstName =  obj.getString("type");
        EmailResponse myResp = new EmailResponse();
        myResp.setValue(value);
        myResp.setType(type);
        //set all other Strings
        //lastly add this object to ArrayList<MyResponse> So you can access all data after saving
    }

}
catch (JSONException e) {
    e.printStackTrace();
}

POJO Class:
public class EmailResponse{
    public String value = "";
    public String type = "";
    //getter setters
}

Hope this helps.


Q:

How do I disable all Source Mapping in Safari DevTools?

In a minified jQuery file I'm using, this snippet at the end: //# sourceMappingURL=jquery.min.map is causing an annoying 404 error to appear in the Developer Console on every refresh.
I don't have the .min.map file and don't intend to get it.
Is there a way I can make Safari DevTools to ignore these annotations and never complain about missing Source Maps? I rarely need that feature.

A:

As far as I know, there is no 'disable source map' option in safari.
I'm also not interested in these red lines in my console log. And tackled the problem from the other end, by letting the server give empty 200 responses for .map files
For nginx it's done by adding the next line to your config
location ~ \.map$ {return 200;}

I know this is dirty, but hey it works...


Q:

iOS convert coordinates from iPhone to iPad compatibility

When I first started programming for iOS (with Cocos2d) I used a bunch of hardcoded coordinates based on 320x480 screen size for the iPhone. I just realized that I need to include at least a basic version of iPad and the iPad mini.
I have read these:
cocos2d (but i'm not sure if this is the best way?)
cocos2d:Convert iPhone App to Universal App
converting coordinates:
Convert coordinates from iPhone screen size to iPad screen size
converting iphone to ipad:
http://iphonedevelopment.blogspot.com/2010/04/converting-iphone-apps-to-universal.html
Apple's documentation on creating universal app:
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html#//apple_ref/doc/uid/TP40007072-CH7-SW24

is there an easy way to convert the graphical display from iPhone to iPad without editing every part of my code where I used a hard coded value? (50 spots, all in 1 file)
what's the best practice for future coding with iOS/Cocos2D coordinates? should I do
#define SPACE_SHIP_X_IPAD 384
#define SPACE_SHIP_X_IPHONE 160
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
`[ship.setPosition ccp:(SPACE_SHIP_X_IPHONE,0)];`

} else {
`[ship.setPosition ccp:(SPACE_SHIP_X_IPAD,0)];`

}
(by the way, will someone who knows how to format this code with the "#" sign, plz teach me how to format the above code?)
is it recommended that I create 2 different apps - one for iphone and one for iPad? or this universal approach of only 1 app, and then selecting the distribution type when I submit to Appstore?
are Mac versions of apps the same distribution channel as the app store for iPhone and iPad? what are the advantages or disadvantages to distributing on Mac as well? (i'm guessing it's not good because graphics would have to accomodate something liek the massive iMac?)
just to make sure - my app file (which doesn't use anything iphone specific like calling) will work on the iPod and iPad Mini without ANY extra work, right?

Any help would be greatly appreciated. I will upvote all good attempts

A:

It looks like your approach is overly complicated.  Making a universal application typically involves never hard-coding position values, but rather calculating these position values based on the bounds of the device.
For example:
//Button in center for universal
CGPoint buttonOffset = CGPointMake( ([[UIScreen mainScreen] bounds].size.width - button.frame.size.width) / 2, ([[UIScreen mainScreen] bounds].size.height - button.frame.size.height) / 2);

button.frame = CGRectMake(buttonOffset.x, buttonOffset.y, button.frame.size.width, button.frame.size.height);

Use similar concepts to create buttons (or ships) with positions that are relative to the screen bounds.  This will save you a lot of time and grief.
One thing to note is that the "bounds" of the screen will not factor in the device orientation.  If you want to support multiple orientations you will find it useful to create a utility method to handle that logic for you.
Something like:
+ (CGSize) deviceSize {
    CGSize size;
    if(UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])){
        size = CGSizeMake([[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width);
    } else {
        size = CGSizeMake([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
    }
    return size;
}

I know you want an easy solution so you don't have to change all your values but I would recommend biting the bullet and changing the values.  It will help you a lot in the long-run.  Not only for this application but the practice will help in any application you create in the future.
Is it recommended that you create two different apps for universal?  No, it is not recommended.  You can select "universal" when creating the xcode project and also change it in an existing project.  You will not need to create two builds or binaries either.  Apple will recognize it as universal and make it available in the store for all devices.  However, you will need to create multiple versions of a splash screen to accommodate different screen sizes and pixel densities.
are Mac versions of apps the same distribution channel as the app store for iPhone and iPad? Sort of... you can deploy to the app store and you gain more freedom since you can package and distribute the OSX binary yourself -- but you will have to create a separate app since you will most likely be using CocoaTouch libraries which are not supported on the mac.  You will want to preserve functionality that does not use CocoaTouch such as your Rendering and Game Logic.  If you are deploying to OSX, the large screen sizes will be the least of your concern.  Advantages: Wider Audience.  Disadvantages: Requires a lot of planning when architecting your app/game so you can reuse as much code as possible and cater to all screens.
just to make sure - my app file (which doesn't use anything iphone specific like calling) will work on the iPod and iPad Mini without ANY extra work, right?  Well... some extra work  With some additional image assets for home screen icons and a splash screen you will be good to go.


Q:

What is system() in linux Terminal?

I am an absolute beginner with Linux Operating system and just for fun in terminal I typed system() what happened next is as below:
satish@satish-Inspiron-N5010 ~ $ system()
>#include<iostream>
>int main()
bash: syntax error near unexpected token 'int'
satish@satish-Ispiron-N5010~ $

Here I want to know that what is system() ? what is it's role here? why I got error in int main() line? What can we do with C/C++ programming in terminal?

A:

Here I want to know that what is system()?

When you said system() and hit Enter, the shell thought that you were about to define a shell function named system.
Anything starting with # is interpreted as a comment by the shell.
You got an error in the int main() line because your function body had not started.
The syntax for a shell function is:
function: function name { COMMANDS ; } or name () { COMMANDS ; }
    Define shell function.

An example of how you might define a function and use it:
$ system()
> { echo $SHELL; }
$ system
/bin/bash


Q:

How to delete specific realm object using for loop

I'm currently trying to delete specific realm object in my model using for loop,
but every time that i execute the deleteFromRealm(i) it stops the loop and I can no longer delete the other object.
I haven't tried any other options though.
final Realm realms = Realm.getDefaultInstance();
        realms.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                RealmResults<CashCountScoreModel> cashCountScoreModels =
                        CashCountScoreModel.getAll(realm);
                for (int i = 0; i < cashCountScoreModels.size(); i++) {
                    if (cashCountScoreModels.get(i) != null && cashCountScoreModels.get(i).isCashOnHand) {
                        Log.d("CheckName : pos -- ",  i +"~~" + cashCountScoreModels.get(i).isCashOnHand);
                        Log.d("CheckName : pos --",  i + "~~" + cashCountScoreModels.get(i).employeeName);
                        cashCountScoreModels.deleteFromRealm(i);
                    //    continue;
                    }
                }
            }
        });

Whenever i try to run the app, and execute this specific code cashCountScoreModels.deleteFromRealm(i);, it stops the loop.

A:

You should not call deleteFromRealm(i) inside a loop because it always causes crash. Use this code instead:
    realms.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmResults<CashCountScoreModel> results = CashCountScoreModel.getAll(realm);
            results.where().equalTo("isCashOnHand", true).findAll().deleteAllFromRealm();
        }
    });


Q:

changing filename extension

I'm trying to change a filename extension from .xlsx to .csv.
I had this syntax so far and works just fine.
raw_file=test_file.xlsx
echo "${raw_file%.xlsx}.csv"
test_file.csv

but if I try to assign .xlsx into variable it doesn't work anymore.
f=.xlsx
echo "${raw_file%.$f}.csv"
test_file.xlsx.csv

what am I doing wrong?

A:

You could use the basename command, e.g.
raw_file=test_file.xlsx
f=.xlsx
echo $(basename "$raw_file" "$f").csv
# -> test_file.csv

But keep in mind that basename also removes any leading directory names from the file name.


Q:

Is it possible to insert your attribute in the HTML-tag?

Is it possible to insert your attribute in the HTML-tag, and then refer to it?
For example, add an attribute group:
first <input type="radio" id="qwerty1" group="1" onClick="myclick();">

second <input type="radio" id="qwerty2" group="2" onClick="myclick();">

third <input type="radio" id="qwerty3" group="3" onClick="myclick();">

A:

Better to use W3C standards attribute data-*
Read More on data- attribute

function myclick(control)
{
alert($(control).attr("data-group"));
}

first <input type="radio" id="qwerty1" data-group="1" onClick="myclick(this);">

second <input type="radio" id="qwerty2" data-group="2" onClick="myclick(this);">

third <input type="radio" id="qwerty3" data-group="3" onClick="myclick(this);">

Update using data() function of jQuery

function myclick(control)
{
alert($(control).data("group"));
}

first <input type="radio" id="qwerty1" data-group="1" onClick="myclick(this);">

second <input type="radio" id="qwerty2" data-group="2" onClick="myclick(this);">

third <input type="radio" id="qwerty3" data-group="3" onClick="myclick(this);">


Q:

Multidemensional Array PHP with the same name

Got a small question. Why this piece of code does only returns one package?
# Packages data
'packages' => [
    'package' => [
        'height' => '100',
        'width' => '200',
    ],
    'package' => [
        'height' => '1300',
        'width' => '2040',
    ],
    'package' => [
        'height' => '1200',
        'width' => '2020',
    ],
]

When I change the names to: packages_1, packages_2, packages_3 they output correctly but when I give them the same name it does only output one package. Is there any way to solve this?

A:

It's because the associative array in PHP is a map so each key must be unique within the same array. You can fix this using one the these method:

Give each of the package keys a unique name (like you've already mentioned in your question).

For example:
'packages' => [
    'package_1' => [
        'height' => '100',
        'width' => '200',
    ],
    'package_2' => [
        'height' => '1300',
        'width' => '2040',
    ],
    'package_3' => [
        'height' => '1200',
        'width' => '2020',
    ],
]

Omit the key entirely and you'll have to access them using indexes.

For example:
'packages' => [
    [
        'height' => '100',
        'width' => '200',
    ],
    [
        'height' => '1300',
        'width' => '2040',
    ],
    [
        'height' => '1200',
        'width' => '2020',
    ],
]

And to access the values:
$myvariable['packages'][0]['height']


Q:

jenkins on kubernetes throws an error with disk space and error in loading the plugins

DISK_SPACE_MEMORY_ISSUEJENKINS_PLUGINS_LOAD_ERRORI have a jenkins server hosted on a kubernetes cluster .There's a 99% of disk space utilized and there n number of plugins installed too.So now the problem is all of sudden the jenkins pipeline type of jobs disappears as there's no pipeline plugin ,got un-installed from the server due to shortage of memory space.When I got into the pod ,I see all the jobs there but doesn't appear on GUI .There's error in loading the plugins too.All I want is to restore the plugins back and back-up the existing jobs too.

A:

I have resolved this by downloading new version jenkins.war and installed it. Increased the Jenkins memory as I was using PVC. Corrected all the versioned plugins by following warning messages .


Q:

How can I create a ColorFunction using Blend?

As shown below, I am trying to find a cool way to show some variance weighted deviation from the mean. There are 10 attributes that I compute the distance for.
How can I add a color function such that it is progressively a darker shade of red when its value is negative (towards the left) and green when the value is positive (towards the right of the graphics)?
distance = {0.245, -0.235, 0.053, -0.048, -0.128,
           -0.007, -0.075, -0.067,-0.005, 0.082}

Show[
  Function[
    attributes,
    Graphics[
      Rectangle[
        {If[distance[[attributes]] < 0, distance[[attributes]]*10, 0],
          attributes - 1},
        {If[distance[[attributes]] < 0, 0, distance[[attributes]]*10],
          attributes}
      ],
      PlotRange -> {{-5, 5}, {0, 10}},
      Epilog -> {White, Line[{{0, 0}, {0, 11}}]}
  ]] /@ Range[10],
 Frame -> True]

A:

distance = {0.245, -0.235, 0.053, -0.048, -0.128, -0.007, -0.075, -0.067, -0.005, 0.082}

Show[Function[attributes,
   Graphics[{Blend[{{-Max[Abs[distance]], Red}, {0, LightRed}, {0,
        LightGreen}, {+Max[Abs[distance]], Green}},
      distance[[attributes]]],
     Rectangle[{If[distance[[attributes]] < 0,
        distance[[attributes]]*10, 0],
       attributes - 1}, {If[distance[[attributes]] < 0, 0,
        distance[[attributes]]*10], attributes}],
     PlotRange -> {{-5, 5}, {0, 10}}},
    Epilog -> {White, Line[{{0, 0}, {0, 11}}]}]] /@ Range[10],
 Frame -> True]

A:

We can achieve such visual style with built-in tools, applying some color gradient along the rectangles. Using your data:
distance = {0.245, -0.235, 0.053, -0.048, -0.128,
           -0.007, -0.075, -0.067,-0.005, 0.082}

BarChart will do the job:
BarChart[distance, ChartElementFunction -> ChartElementDataFunction[
"GradientScaleRectangle", "ColorScheme"-> "DarkRainbow"], BarOrigin ->Left,
AspectRatio ->1, Frame ->True, GridLines -> {Range[-.22, .24, .02], Automatic}]

The horizontal scale is a bit different than yours, but you can easily adjust it. I personally enjoy very much that just a few lines will do things like:
BarChart[RandomReal[{-1, 1}, {50, 50}], ChartLayout -> "Stacked", Axes -> None,
BarSpacing ->{0, 0}, PerformanceGoal ->"Speed", ChartStyle -> "AvocadoColors"]

That was a Documentation example.

A:

Looking at David's answer, it seems to me that you might want to

explicitly target the maximum and minimum values in your dataset to be pure green and red, respectively; and
have a neutral color, like gray, as the color at 0, so as to avoid the brownish colors in the middle.

To that end, I used this for the color:
If[distance[[attributes]] < 0,
 Blend[{{Min[distance], Red}, {0, Gray}}, distance[[attributes]]],
 Blend[{{Max[distance], Green}, {0, Gray}}, distance[[attributes]]]]


Q:

JavaFX for iphone ipad

i need to know that can JavaFX application run into IPHONE IPAD?
Is there any JavaFX runtime in these device.

A:

No it can't.  The ipad cannot run JavaFX, Flash, Silverlight, or Java Applets.  Apple has explicitly not allowed these.  The basic options are HTML5/Javascript apps on the web or native apps which run on your phone.  If you want to run Java on an ipad, the closest you can come is GWT which you can use to write a web app and host on a server.  It cannot be installed on the phone as a native app (except perhaps through PhoneGap).  The ipad user would then access your app through the web browser.
If you are serious about writing apps for a phone in Java, you should consider Android.  You can write Android apps in Java, though again not in JavaFX.
[EDIT]
Apparently this has changed since I first answered this question as seen in this post.  It is now possible to run JavaFX on ios.


Q:

Guidelines regarding spaces for class variables, instance variables, etc

Is there a guideline to follow in regard to space for class variables, instance variables, etc? For example
class MyModel < ApplicationRecord
  belongs_to :something
  has_many: :something_elses
  validates: :property, presence: true
  after_save :do_something
end

In this case I'm using as example a model record, but I would like to understand the standard style for everything. I'm using Rubocop and it doesn't tell me anything about this.
Thanks.

A:

anothermh shared the link above (and for the record, amazing that their profile photo is of Robocop when this question is about Rubocop) ... but here's what the Rubocop guidelines for classes suggest:
class Person
  # extend and include go first
  extend SomeModule
  include AnotherModule

  # inner classes
  CustomError = Class.new(StandardError)

  # constants are next
  SOME_CONSTANT = 20

  # afterwards we have attribute macros
  attr_reader :name

  # followed by other macros (if any)
  validates :name

  # public class methods are next in line
  def self.some_method
  end

  # initialization goes between class methods and other instance methods
  def initialize
  end

  # followed by other public instance methods
  def some_method
  end

  # protected and private methods are grouped near the end
  protected

  def some_protected_method
  end

  private

  def some_private_method
  end
end

As a personal note: although having consistent styling makes it quicker and easier to read code and for others to scan what you're written, keep in mind that these are just recommendations of "best practices". At the end of the day whatever works best FOR YOU should be your new best practice.


Q:

HttpURLConnection.getInputStream() hangs and never finishes

I am attempting to get a token from a JSON endpoint using the following code:
public class FetchToken extends AsyncTask<String, Void, Void> {
    String data = "";
    String token = "";

    public TokenDelegate delegate = null;

    @Override
    protected Void doInBackground(String... identity) {
        try {
            if (identity.length == 1) {
                URL url = new URL(identity[0]);

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";

                while (line != null) {
                    line = bufferedReader.readLine();
                    data = data + line;
                }

                JSONObject JO = new JSONObject(data);
                token = JO.get("token").toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Log.d("token", token);
        //delegate.processFinish(token);
        super.onPostExecute(aVoid);
    }
}

I have tried printing to the debug log after every line, and it seems that the line InputStream inputStream = httpURLConnection.getInputStream(); never finishes, nor does the rest of the code get executed. However, this is taking place inside of an AsyncTask, and the onPostExecute method of that AsyncTask is firing as if the task has been completed, which it doesn't seem as if it has been.
None of the catch blocks are being executed, it seems like, and when I inspect the Network panel in the Android Profiler then the request says it is not passing anything back. However, accessing the JSON endpoint in browser brings everything back correctly.
Hopefully someone knows what the problem may be. I've attempted to google things to no avail. Let me know if more information is needed. Thanks.

A:

The line InputStream inputStream = httpURLConnection.getInputStream(); was never completing because it was throwing a java.security.cert.CertPathValidatorException. The error was not being logged because I was not catching this type of error in my try / catch block.

A:

Have a look at below code and modify your code accordingly.
1) if method is GET, then data or headers can be null.
Example usage
 url = <some url>
 Map<String, String> headers = new HashMap<String, String>();
 headers.put("Content-Type", "application/json");
 headers.put("Accept", "application/json");

a) GET :
invokeHTTPRequest(url, "GET", headers, null);

b) POST
Student st = new Student();
Gson gson = new Gson();
String jsonReqData = gson.toJson(st);
String resp = invokeHTTPRequest3(url, "POST", headers,  jsonReqData);

public static String invokeHTTPRequest(String urlString, String method, Map headers,String data) {
    URL url = null;
    try {
        url = new URL(urlString);
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.setRequestProperty(header.getKey(), header.getValue());
            }
        }

        if (data != null) {
            byte[] postDataBytes = data.toString().getBytes();
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postDataBytes);

        }

        BufferedReader rd = null;

        if(conn.getResponseCode() == 200){
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        }
        else{
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }

        StringBuilder result = new StringBuilder();

        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();

        return result.toString();

    } catch (Exception e) {
        //handle exception here
    }

}


Q:

How to change gradient settings for muliple equal objects at the same time?

I have multiple objects with equal gradients in Adobe Illustrator. Anyone knows how can I change gradient settings for all of the objects at once?

A:

You can use Edit -> Edit Colors -> Recolor Artwork. You can see all colors here and you can edit / replace them.


Q:

Matching a single character within a string in R

Im assert if there is a "." in a string in R, but grepl always comes back false. Can anyone explain where im going wrong?
Here is my code:
grepl("testtxt",".")
[1] FALSE
grepl("test.txt",".")
[1] FALSE

A:

We need either fixed = TRUE
grepl("test.txt", pattern = ".", fixed = TRUE)
#[1] TRUE

NOTE: pattern is the first argument of grep/grepl  If we specify it in different order, make sure to name the parameter
or escape (\\.) the . as . is a metacharacter that matches any character


Q:

What factors cause something to resist wind?

Hi, this is a very basic question from a physics know-nothing. I've tried googling it every way I could think of, but either couldn't find or recognize the answer.  I thought I might have better luck asking someone with the framework already in place. Thanks for your patience.

The Question: I want to understand what factors matter when deciding whether a given motionless object will get blown away by a gust of wind, or stay in place, and how those factors relate to each other.
As best I understand, in physics wind is understood as a kind of drag. So what causes an otherwise motionless object to resist drag? Mass? Weight? Surface area? Density? Is it understood as a simple force meeting an object, or is there more to it?

A:

In physics, wind is understood as a drift of particles. Basically the air molecules, which are moving due to temperature, on average move in a certain direction (without wind they still move, but on average stay at their position).
Air molecules hitting an object are deflected, causing a force on the object - a drag. How big that force is depends mainly on three factors:

The number of molecules hitting the object.
The velocity of the molecules hitting the object.
The angle under which the molecule hits the object.

Obviously the strength of the wind influences both the velocity and the number of molecules hitting your object, its direction might influence the angle.
The characteristics of your object also influence this force. Let's take a sail as an example.
Size matters here, to be more precise: area. The bigger the sail, the more force. Depending on the wind you might be able to hold a scarf like a sail in the wind, but bigger sails move entire ships across the ocean.
Shape matters as well. If the sail just waves like a flag, the wind "slides along" the sail instead of hitting it directly (remember the angle part?). "Streamlined" objects (e.g. racing cars) especially try find a good shape.
Against all that drag caused by the wind, there are usually other forces.
The weight of an object combined with its friction on the ground. Or some screws/foundations holding it in place. Magnets holding things in place. Or whatever else causes a force on the object.
If your object moves or not is now just a question of which force is stronger and can get quite complicated. Heavy objects might slide away on ice but not on earth. A plastic bag might hang somewhere until the next gust hits. A sail will probably move and take an entire ship with it - but only if the wind hits from the right direction.


Q:

TypeError object is not a function when parsing object

I am attempting to parse the values below based on a search criteria and then print the result to a table. I am able to correctly parse the desired results to console or print all the results to a table. Below is my attempt to merge both functions. I end up with a type error TypeError: obj.list[i].forEach is not a function. From searching, I believe it is because it is an object and not an array though have been unable to parse the object correctly. How can I correct the issue in order to correctly parse the object?

var obj = {
  "list": [{
      "name": "my Name",
      "id": 12,
      "type": "car owner"
    },
    {
      "name": "my Name",
      "id": 13,
      "type": "car owner2"
    },
    {
      "name": "my Name4",
      "id": 14,
      "type": "car owner3"
    },
    {
      "name": "my Name4",
      "id": 15,
      "type": "car owner5"
    }
  ]
};

var tableBody = "";

var columns = [];

// Create the header record.
tableBody = tableBody + "
";
for (var prop in obj.list[0]) {
  if (obj.list[0].hasOwnProperty(prop)) {
    // Append properties such as myid, fname, lname etc.
    tableBody = tableBody + ("" + prop + "	");

    // Also keep a list of columns, that can be used later to get column values from the 'data' object.
    columns.push(prop);
  }
}
tableBody = tableBody + "
";

var results = [];
var searchField = "name";
var searchVal = "my Name";
for (var i = 0; i < obj.list.length; i++) {
  // search term
  if (obj.list[i][searchField] == searchVal) {
    // Create the data rows.
    // I get an error here:
    obj.list[i].forEach(function(row) {
      // Create a new row in the table for every element in the data array.
      tableBody = tableBody + "
";

      columns.forEach(function(cell) {
        // Cell is the property name of every column.
        // row[cell] gives us the value of that cell.
        tableBody = tableBody + "" + row[cell] + "	";
      });

      tableBody = tableBody + "
";
    });
  }
}

jQuery("#usersTable").append(tableBody);

JSFiddle
Working version based on feedback

A:

forEach is an iteration method for arrays, in provided code you're trying to apply this method to object, it's a wrong way. To iterate through object properties you can use for (var key in object) {"code here"}. I have corrected your code:

var obj = {
  "list": [{
      "name": "my Name",
      "id": 12,
      "type": "car owner"
    },
    {
      "name": "my Name",
      "id": 13,
      "type": "car owner2"
    },
    {
      "name": "my Name4",
      "id": 14,
      "type": "car owner3"
    },
    {
      "name": "my Name4",
      "id": 15,
      "type": "car owner5"
    }
  ]
};

var tableBody = "";
var columns = [];
var searchField = "name";
var searchVal = "my Name";

tableBody = tableBody + "
";
for (var prop in obj.list[0]) {
  if (obj.list[0].hasOwnProperty(prop)) {
    tableBody = tableBody + ("" + prop + "	");
    columns.push(prop);
  }
}

tableBody = tableBody + "
";

for (var i = 0; i < obj.list.length; i++) {
  if (obj.list[i][searchField] == searchVal) {
    tableBody = tableBody + "
";
    for (var key in obj.list[i]) {
      tableBody = tableBody + "" + obj.list[i][key] + "	";
    };
    tableBody = tableBody + "
";
  }
}

jQuery("#usersTable").append(tableBody);


Q:

Parse PFQuery Include key not working

I have a class, Business:
header:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>

@interface Business : PFObject <PFSubclassing>

+ (NSString *)parseClassName;
@property (retain) NSString *name;
@property (retain) NSString *shortName;
@property (retain) PFFile *logo;
@property (retain) PFFile *banner;

@end

implementation:
#import "Business.h"
#import <Parse/PFObject+Subclass.h>

@implementation Business

@dynamic name;
@dynamic shortName;
@dynamic logo;
@dynamic banner;

+ (NSString *)parseClassName
{
    return @"Business";
}

@end

And a class, Relation
header:
#import <Parse/Parse.h>
#import "Business.h"

@interface Relation : PFObject <PFSubclassing>

@property (retain) PFUser *user;
@property (retain) Business *business;

@end

implementation
#import "Relation.h"
#import <Parse/PFObject+Subclass.h>

@implementation Relation

@dynamic business;
@dynamic user;

+ (NSString *)parseClassName
{
    return @"Relation";
}

@end

I'm making a Relation Query, hoping to find Businesses that are related to certain users, like so:
PFQuery *query = [Relation query];
[query includeKey:[Business parseClassName]];
[query whereKey:@"user" equalTo:[PFUser currentUser]];

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    NSMutableArray *businesses = [NSMutableArray array];
    if (objects.count) {
        for (Relation *relation in objects) {
            [businesses addObject:relation.business];
        }
    }

    block(businesses, objects, error);
}];

It does appear that I am successfully retrieving the businesses that I want to retrieve. However, it seems that the Business class is missing some of its columns. I made sure to make use of PFQuery's include key so that the Business class would return all of its properties, but the only property it seems to include is its object ID.
(lldb) po businesses <__NSArrayM 0x174050b60>( <Business: 0x170118810, objectId: 7Sdh8a0d8, localId: (null)> { } )

Sorry I've included so much code, I just feel like my error could be anywhere. Why isn't my query returning the full Business object?
Thanks!

A:

Ah, I was being stupid. It was all in the
[Business parseClassName]

I was requesting key "Business" instead of "business"


Q:

How does Task Manager gets command line executable path for processes?

I'm looking at Task Manager's list of processes, and enabled View > Select columns > Command line to see include exe path & command line arguments.
I tried to get the same thing working using GetModuleFileNameEx but there's some problems; first, the result doesn't include any arguments and it also fails for some processes, as basic as WinRar.exe or Opera.exe.
I know that Task Manager uses WMI to get some of this data (I tried shutting down the service and it failed just the way my script did, for the same processes), but I wonder, what makes a process's path "ungettable"?

A:

Task Manager uses the process's PEB structure to access the command-line arguments (amongst other things).  If you have a HANDLE to the target process (and sufficient rights to access its memory), you can access the PEB using the NtQueryInformationProcess() function (set its ProcessInformationClass parameter to ProcessBasicInformation to receive a PROCESS_BASIC_INFORMATION structure) to obtain the memory address of the PEB within the target process's address space (amongst other things).  You can then use ReadProcessMemory() to read the contents of the PEB into your app's address space as needed.  The command-line parameters are located by using the PEB::ProcessParameters field, which is a pointer to a RTL_USER_PROCESS_PARAMETERS structure, which contains a CommandLine field of type UNICODE_STRING.
Things get a little trickier if you are a 32-bit process accessing the PEB of a 64-bit process, or vice versa.  You have to take into account the different sizes of pointers (4 of 32-bit, 8 for 64-bit), which affects structure sizes and offsets.
But this is the gist of it.


Q:

How to execute another python script from your script and be able to debug?

You have wrapper python script that is calling another python script, currently using os.system('python another.py some-params').
You want to be able to debug both scripts and if you use os.system() you'll loose the debugger, so it does make sense to load the second script using the same interpretor instead of starting another one.
import doesn't to the expected thing because it does not run the __main__.
Other variants, like exec() or runpy seams to miss the argv parameters.
What solution do you see for this issue?
I'm looking for a solution that does not require you to modify the another.py script. Probably this will require to modify the sys.argv before executing it.

A:

So far I found a solution that works only with Python 2.7+ (runpy.run_path() was introduced in Python 2.7).
If you can find one that works with 2.6 (or even 2.5) you are welcome to post it.
import runpy, sys
saved_argv = sys.argv
... # patch sys.argv[1:] and load new command line parameters
# run_path() does change only sys.argv[0] but restores it
runpy.run_path('another.py', run_name="__main__")
sys.argv = saved_argv # restore sys.argv

A:

Based on the recommendation received from EOL, I made an extension to execfile() that does solve its limitations execfile2()
Below is the code, but newer versions will be published here. It is backwards compatible with execfile().
def execfile2(filename, _globals=dict(), _locals=dict(), cmd=None, quiet=False):
    _globals['__name__']='__main__'
    saved_argv = sys.argv # we save sys.argv
    if cmd:
    sys.argv=list([filename])
            if isinstance(cmd , list):
                sys.argv.append(cmd)
            else:
                sys.argv.extend(shlex.split(cmd))
    exit_code = 0
try:
        execfile(filename, _globals, _locals)
    except SystemExit as e:
        if isinstance(e.code , int):
            exit_code = e.code # this could be 0 if you do sys.exit(0)
        else:
            exit_code = 1
    except Exception:
        if not quiet:
            import traceback
            traceback.print_exc(file=sys.stderr)
        exit_code = 1
    finally:
        if cmd:
            sys.argv = saved_argv # we restore sys.argv
    return exit_code